diff --git a/assets/Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js b/assets/Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js similarity index 87% rename from assets/Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js rename to assets/Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js index f9f8bb09e67cf0a5a26d8d7a69bb2f06e7149b30..034aac41afafb4d83508b76c5024123df34ec74c 100644 --- a/assets/Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js +++ b/assets/Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js @@ -1 +1 @@ -import{_ as d}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import{d as p,bF as m,bG as f,af as b,c,o as v,p as r,b as y,bS as u,bT as V,y as C,C as g,bQ as k,a as s,bH as x,D as i}from"./index-rD0Uu1v9.js";const B={op50:""},w=p({__name:"Collapsable",props:m({default:{type:Boolean},label:null},{modelValue:{type:Boolean,default:!1},modelModifiers:{}}),emits:["update:modelValue"],setup(o){const t=o,e=f(o,"modelValue");b(()=>{t.default!=null&&(e.value=!!t.default)});function n(l){return e.value=l,l}return(l,a)=>(v(),c("div",null,[r(l.$slots,"trigger",u(V({visible:e.value,setVisible:n})),()=>[s("button",{sticky:"","top-0":"","z-10":"",flex:"","items-center":"","justify-between":"",px2:"",py1:"","text-sm":"","backdrop-blur-xl":"",onClick:a[0]||(a[0]=_=>e.value=!e.value)},[s("span",null,i(t.label??"Collapsable"),1),a[1]||(a[1]=x()),s("span",B,i(e.value?"▲":"▼"),1)])]),y(d,null,{default:C(()=>[e.value?r(l.$slots,"default",u(k({key:0},{visible:e.value,setVisible:n}))):g("",!0)]),_:3})]))}});export{w as _}; +import{_ as d}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import{d as p,bF as m,bG as f,af as b,c,o as v,p as r,b as y,bS as u,bT as V,y as C,C as g,bQ as k,a as s,bH as x,D as i}from"./index-Dlp4W1Zl.js";const B={op50:""},w=p({__name:"Collapsable",props:m({default:{type:Boolean},label:null},{modelValue:{type:Boolean,default:!1},modelModifiers:{}}),emits:["update:modelValue"],setup(o){const t=o,e=f(o,"modelValue");b(()=>{t.default!=null&&(e.value=!!t.default)});function n(l){return e.value=l,l}return(l,a)=>(v(),c("div",null,[r(l.$slots,"trigger",u(V({visible:e.value,setVisible:n})),()=>[s("button",{sticky:"","top-0":"","z-10":"",flex:"","items-center":"","justify-between":"",px2:"",py1:"","text-sm":"","backdrop-blur-xl":"",onClick:a[0]||(a[0]=_=>e.value=!e.value)},[s("span",null,i(t.label??"Collapsable"),1),a[1]||(a[1]=x()),s("span",B,i(e.value?"▲":"▼"),1)])]),y(d,null,{default:C(()=>[e.value?r(l.$slots,"default",u(k({key:0},{visible:e.value,setVisible:n}))):g("",!0)]),_:3})]))}});export{w as _}; diff --git a/assets/FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js b/assets/FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js similarity index 81% rename from assets/FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js rename to assets/FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js index 10a169c65188b5004bb7b768ffe9e15987ca03b8..7ee83e4108ec391701e781f8b216120de2f400ae 100644 --- a/assets/FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js +++ b/assets/FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js @@ -1 +1 @@ -import{_ as m}from"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";import{d as p,h as x,c as o,o as n,a as l,b as V,bH as f,C as h,D as d,z as v}from"./index-rD0Uu1v9.js";const y={"max-w-full":""},C={flex:"~ col gap-4"},_={class:"flex items-center gap-1 text-sm font-medium"},b={key:0,class:"text-red-500"},g={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},N=p({__name:"FieldInput",props:{modelValue:null,label:null,description:null,placeholder:null,required:{type:Boolean},type:null,inputClass:null},emits:["update:modelValue"],setup(e,{emit:u}){const c=e,i=u,t=x({get:()=>c.modelValue,set:a=>i("update:modelValue",a)});return(a,s)=>(n(),o("div",y,[l("label",C,[l("div",null,[l("div",_,[f(d(e.label)+" ",1),e.required!==!1?(n(),o("span",b,"*")):h("",!0)]),l("div",g,d(e.description),1)]),V(m,{modelValue:t.value,"onUpdate:modelValue":s[0]||(s[0]=r=>t.value=r),type:e.type,placeholder:e.placeholder,class:v(e.inputClass)},null,8,["modelValue","type","placeholder","class"])])]))}});export{N as _}; +import{_ as m}from"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";import{d as p,h as x,c as o,o as n,a as l,b as V,bH as f,C as h,D as d,z as v}from"./index-Dlp4W1Zl.js";const y={"max-w-full":""},C={flex:"~ col gap-4"},_={class:"flex items-center gap-1 text-sm font-medium"},b={key:0,class:"text-red-500"},g={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},N=p({__name:"FieldInput",props:{modelValue:null,label:null,description:null,placeholder:null,required:{type:Boolean},type:null,inputClass:null},emits:["update:modelValue"],setup(e,{emit:u}){const c=e,i=u,t=x({get:()=>c.modelValue,set:a=>i("update:modelValue",a)});return(a,s)=>(n(),o("div",y,[l("label",C,[l("div",null,[l("div",_,[f(d(e.label)+" ",1),e.required!==!1?(n(),o("span",b,"*")):h("",!0)]),l("div",g,d(e.description),1)]),V(m,{modelValue:t.value,"onUpdate:modelValue":s[0]||(s[0]=r=>t.value=r),type:e.type,placeholder:e.placeholder,class:v(e.inputClass)},null,8,["modelValue","type","placeholder","class"])])]))}});export{N as _}; diff --git a/assets/HeaderLink-0aZMXKsY.js b/assets/HeaderLink-Dg_3MlXg.js similarity index 90% rename from assets/HeaderLink-0aZMXKsY.js rename to assets/HeaderLink-Dg_3MlXg.js index d1c40db18bac8dc62e3592351d0a7adbd8205502..d9f62777f35135cd3d1ead743bb665d9feff8873 100644 --- a/assets/HeaderLink-0aZMXKsY.js +++ b/assets/HeaderLink-Dg_3MlXg.js @@ -1 +1 @@ -import{d as r,bC as c,x as l,e,bo as d,o as s,y as _,c as t,a,bn as i}from"./index-rD0Uu1v9.js";const k="/assets/logo-dark-CO0kwKsz.svg",p="/assets/logo-D6zeZTFl.svg",u=["src"],m=["src"],x=r({__name:"HeaderLink",setup(g){const n=c();return(f,o)=>(s(),l(e(d),{to:"/",flex:"~","items-center":"","gap-2":"","px-2":"","text-nowrap":"","text-2xl":"","outline-none":""},{default:_(()=>[e(n)?(s(),t("img",{key:0,src:e(k),"h-8":"","w-8":"",class:"theme-colored"},null,8,u)):(s(),t("img",{key:1,src:e(p),"h-8":"","w-8":"",class:"theme-colored"},null,8,m)),o[0]||(o[0]=a("div",{"font-cute":""},[a("span",null,"アイリ")],-1))]),_:1}))}}),w=i(x,[["__scopeId","data-v-496b6cde"]]);export{w as H}; +import{d as r,bC as c,x as l,e,bo as d,o as s,y as _,c as t,a,bn as i}from"./index-Dlp4W1Zl.js";const k="/assets/logo-dark-CO0kwKsz.svg",p="/assets/logo-D6zeZTFl.svg",u=["src"],m=["src"],x=r({__name:"HeaderLink",setup(g){const n=c();return(f,o)=>(s(),l(e(d),{to:"/",flex:"~","items-center":"","gap-2":"","px-2":"","text-nowrap":"","text-2xl":"","outline-none":""},{default:_(()=>[e(n)?(s(),t("img",{key:0,src:e(k),"h-8":"","w-8":"",class:"theme-colored"},null,8,u)):(s(),t("img",{key:1,src:e(p),"h-8":"","w-8":"",class:"theme-colored"},null,8,m)),o[0]||(o[0]=a("div",{"font-cute":""},[a("span",null,"アイリ")],-1))]),_:1}))}}),w=i(x,[["__scopeId","data-v-496b6cde"]]);export{w as H}; diff --git a/assets/IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js b/assets/IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js similarity index 95% rename from assets/IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js rename to assets/IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js index 2470996b3177d4f8b53e2af9606f88c27258d75f..a28789c5037ba6fd5a38dd67647f74ca4ae56ac1 100644 --- a/assets/IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js +++ b/assets/IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js @@ -1 +1 @@ -import{d as m,g as s,w as p,h,c as f,o as x,n as l,a as u,z as y}from"./index-rD0Uu1v9.js";const C=m({__name:"IconAnimation",props:{icon:null,iconSize:null,position:null,duration:null,started:{type:Boolean},textColor:null,isReverse:{type:Boolean},zIndex:null},emits:["animationEnded"],setup(a,{emit:d}){const e=a,c=d,n=s(!1);p(()=>e.started,o=>{o&&requestAnimationFrame(()=>{n.value=!0})});const t=h(()=>({opacity:n.value!==e.isReverse?1:0,size:n.value!==e.isReverse?25:e.iconSize,position:n.value!==e.isReverse?"calc(50dvw - 12.5rem), calc(50dvh - 12.5rem)":e.position,textColor:n.value!==e.isReverse?"text-white":e.textColor})),i=s([]),r=s(!1);function v(o){i.value.push(o.propertyName),i.value.includes("color")&&i.value.includes("width")&&i.value.includes("height")&&i.value.includes("transform")&&(r.value=!0,c("animationEnded"))}return(o,z)=>(x(),f("div",{"pointer-events-none":"",fixed:"",w:"100dvw",h:"100dvh",style:l({zIndex:r.value?a.zIndex:void 0})},[u("div",{"bg-primary-500":"",fixed:"","inset-0":"","transition-opacity":"","ease-linear":"",style:l({opacity:t.value.opacity,transitionDuration:`${a.duration}ms`})},null,4),u("div",{fixed:"","inset-0":"","ease-in-out":"",style:l({width:`${t.value.size}rem`,height:`${t.value.size}rem`,transform:`translate(${t.value.position})`,transitionDuration:`${a.duration}ms`}),class:y([t.value.textColor,e.icon,{"transition-all":n.value}]),onTransitionend:v},null,38)],4))}});export{C as _}; +import{d as m,g as s,w as p,h,c as f,o as x,n as l,a as u,z as y}from"./index-Dlp4W1Zl.js";const C=m({__name:"IconAnimation",props:{icon:null,iconSize:null,position:null,duration:null,started:{type:Boolean},textColor:null,isReverse:{type:Boolean},zIndex:null},emits:["animationEnded"],setup(a,{emit:d}){const e=a,c=d,n=s(!1);p(()=>e.started,o=>{o&&requestAnimationFrame(()=>{n.value=!0})});const t=h(()=>({opacity:n.value!==e.isReverse?1:0,size:n.value!==e.isReverse?25:e.iconSize,position:n.value!==e.isReverse?"calc(50dvw - 12.5rem), calc(50dvh - 12.5rem)":e.position,textColor:n.value!==e.isReverse?"text-white":e.textColor})),i=s([]),r=s(!1);function v(o){i.value.push(o.propertyName),i.value.includes("color")&&i.value.includes("width")&&i.value.includes("height")&&i.value.includes("transform")&&(r.value=!0,c("animationEnded"))}return(o,z)=>(x(),f("div",{"pointer-events-none":"",fixed:"",w:"100dvw",h:"100dvh",style:l({zIndex:r.value?a.zIndex:void 0})},[u("div",{"bg-primary-500":"",fixed:"","inset-0":"","transition-opacity":"","ease-linear":"",style:l({opacity:t.value.opacity,transitionDuration:`${a.duration}ms`})},null,4),u("div",{fixed:"","inset-0":"","ease-in-out":"",style:l({width:`${t.value.size}rem`,height:`${t.value.size}rem`,transform:`translate(${t.value.position})`,transitionDuration:`${a.duration}ms`}),class:y([t.value.textColor,e.icon,{"transition-all":n.value}]),onTransitionend:v},null,38)],4))}});export{C as _}; diff --git a/assets/IconStatusItem-BolEMtws.js b/assets/IconStatusItem-BxiCMDHT.js similarity index 97% rename from assets/IconStatusItem-BolEMtws.js rename to assets/IconStatusItem-BxiCMDHT.js index 2e9df8cfc4195f646083bbe41c2d05ca76748145..29fdf81a094c17dbb992220695946d9c34ea4cd6 100644 --- a/assets/IconStatusItem-BolEMtws.js +++ b/assets/IconStatusItem-BxiCMDHT.js @@ -1 +1 @@ -import{d as u,r as c,c as e,o as n,b as d,a as o,y as m,C as a,D as s,z as i,bn as _}from"./index-rD0Uu1v9.js";const p={flex:"~ col",bg:"neutral-200/50 dark:neutral-700",border:"neutral-100 dark:neutral-700 hover:primary-500/30 dark:hover:primary-400/30 solid 2","drop-shadow":"none hover:[0px_4px_4px_rgba(220,220,220,0.4)] active:[0px_0px_0px_rgba(220,220,220,0.25)] dark:hover:none",class:"menu-icon-status-item",transition:"all ease-in-out duration-400","w-full":"","cursor-pointer":"","of-hidden":"","rounded-xl":""},g={"z-1":"","flex-1":""},h={"text-lg":"","font-bold":"",class:"menu-icon-status-item-title",transition:"all ease-in-out duration-400"},k={text:"sm neutral-500 dark:neutral-400",class:"menu-icon-status-item-description",transition:"all ease-in-out duration-400"},f=["src"],x={"p-2":""},v={key:0,"size-3":"",bg:"green-500 dark:green-600","rounded-full":""},y={key:1,"size-3":"",bg:"neutral-400 dark:neutral-500","rounded-full":""},b=u({__name:"IconStatusItem",props:{title:null,description:null,icon:null,iconColor:null,iconImage:null,to:null,configured:{type:Boolean}},setup(r){const t=r;return(C,I)=>{const l=c("RouterLink");return n(),e("div",p,[d(l,{flex:"~ row",class:"menu-icon-status-item-link",bg:"neutral-50 dark:neutral-800",transition:"all ease-in-out duration-400",relative:"","h-full":"","w-full":"","items-center":"","overflow-hidden":"","rounded-lg":"","p-5":"","text-left":"",to:t.to},{default:m(()=>[o("div",g,[o("div",h,s(t.title),1),o("div",k,[o("span",null,s(t.description),1)])]),t.icon?(n(),e("div",{key:0,class:i(["menu-icon-status-item-icon",[t.icon]]),transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-16":"","translate-y-2":"",text:"neutral-400/50 dark:neutral-600/50","grayscale-100":""},null,2)):a("",!0),t.iconColor?(n(),e("div",{key:1,class:i(["menu-icon-status-item-icon-color",[t.iconColor]]),transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-16":"","translate-y-2":"",text:"neutral-400/50 dark:neutral-600/50","grayscale-100":""},null,2)):a("",!0),t.iconImage?(n(),e("img",{key:2,src:t.iconImage,class:"menu-icon-status-item-icon-image",transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-16":"","translate-y-2":"","grayscale-100":""},null,8,f)):a("",!0)]),_:1},8,["to"]),o("div",x,[t.configured?(n(),e("div",v)):(n(),e("div",y))])])}}}),w=_(b,[["__scopeId","data-v-883ae105"]]);export{w as I}; +import{d as u,r as c,c as e,o as n,b as d,a as o,y as m,C as a,D as s,z as i,bn as _}from"./index-Dlp4W1Zl.js";const p={flex:"~ col",bg:"neutral-200/50 dark:neutral-700",border:"neutral-100 dark:neutral-700 hover:primary-500/30 dark:hover:primary-400/30 solid 2","drop-shadow":"none hover:[0px_4px_4px_rgba(220,220,220,0.4)] active:[0px_0px_0px_rgba(220,220,220,0.25)] dark:hover:none",class:"menu-icon-status-item",transition:"all ease-in-out duration-400","w-full":"","cursor-pointer":"","of-hidden":"","rounded-xl":""},g={"z-1":"","flex-1":""},h={"text-lg":"","font-bold":"",class:"menu-icon-status-item-title",transition:"all ease-in-out duration-400"},k={text:"sm neutral-500 dark:neutral-400",class:"menu-icon-status-item-description",transition:"all ease-in-out duration-400"},f=["src"],x={"p-2":""},v={key:0,"size-3":"",bg:"green-500 dark:green-600","rounded-full":""},y={key:1,"size-3":"",bg:"neutral-400 dark:neutral-500","rounded-full":""},b=u({__name:"IconStatusItem",props:{title:null,description:null,icon:null,iconColor:null,iconImage:null,to:null,configured:{type:Boolean}},setup(r){const t=r;return(C,I)=>{const l=c("RouterLink");return n(),e("div",p,[d(l,{flex:"~ row",class:"menu-icon-status-item-link",bg:"neutral-50 dark:neutral-800",transition:"all ease-in-out duration-400",relative:"","h-full":"","w-full":"","items-center":"","overflow-hidden":"","rounded-lg":"","p-5":"","text-left":"",to:t.to},{default:m(()=>[o("div",g,[o("div",h,s(t.title),1),o("div",k,[o("span",null,s(t.description),1)])]),t.icon?(n(),e("div",{key:0,class:i(["menu-icon-status-item-icon",[t.icon]]),transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-16":"","translate-y-2":"",text:"neutral-400/50 dark:neutral-600/50","grayscale-100":""},null,2)):a("",!0),t.iconColor?(n(),e("div",{key:1,class:i(["menu-icon-status-item-icon-color",[t.iconColor]]),transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-16":"","translate-y-2":"",text:"neutral-400/50 dark:neutral-600/50","grayscale-100":""},null,2)):a("",!0),t.iconImage?(n(),e("img",{key:2,src:t.iconImage,class:"menu-icon-status-item-icon-image",transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-16":"","translate-y-2":"","grayscale-100":""},null,8,f)):a("",!0)]),_:1},8,["to"]),o("div",x,[t.configured?(n(),e("div",v)):(n(),e("div",y))])])}}}),w=_(b,[["__scopeId","data-v-883ae105"]]);export{w as I}; diff --git a/assets/Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js b/assets/Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js similarity index 91% rename from assets/Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js rename to assets/Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js index fb85be10d45c35657d31e521e2e9517d0cf5740f..10fdf31d74e4c22028a531b1b725ed254640dbee 100644 --- a/assets/Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js +++ b/assets/Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js @@ -1 +1 @@ -import{d as r,bF as n,bG as u,A as s,ch as d,o as i,c as p}from"./index-rD0Uu1v9.js";const m=["type"],y=r({__name:"Input",props:n({type:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const l=e,t=u(e,"modelValue");return(c,a)=>s((i(),p("input",{"onUpdate:modelValue":a[0]||(a[0]=o=>t.value=o),type:l.type||"text",border:"focus:primary-100 dark:focus:primary-400/50 2 solid neutral-200 dark:neutral-800",transition:"all duration-200 ease-in-out",text:"disabled:neutral-400 dark:disabled:neutral-600",cursor:"disabled:not-allowed","w-full":"","rounded-lg":"","px-2":"","py-1":"","text-nowrap":"","text-sm":"","outline-none":"",shadow:"sm",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900"},null,8,m)),[[d,t.value]])}});export{y as _}; +import{d as r,bF as n,bG as u,A as s,ch as d,o as i,c as p}from"./index-Dlp4W1Zl.js";const m=["type"],y=r({__name:"Input",props:n({type:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const l=e,t=u(e,"modelValue");return(c,a)=>s((i(),p("input",{"onUpdate:modelValue":a[0]||(a[0]=o=>t.value=o),type:l.type||"text",border:"focus:primary-100 dark:focus:primary-400/50 2 solid neutral-200 dark:neutral-800",transition:"all duration-200 ease-in-out",text:"disabled:neutral-400 dark:disabled:neutral-600",cursor:"disabled:not-allowed","w-full":"","rounded-lg":"","px-2":"","py-1":"","text-nowrap":"","text-sm":"","outline-none":"",shadow:"sm",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900"},null,8,m)),[[d,t.value]])}});export{y as _}; diff --git a/assets/Model.vue_vue_type_script_setup_true_lang-DfGKadm0.js b/assets/Model.vue_vue_type_script_setup_true_lang-CSqfK4Nz.js similarity index 97% rename from assets/Model.vue_vue_type_script_setup_true_lang-DfGKadm0.js rename to assets/Model.vue_vue_type_script_setup_true_lang-CSqfK4Nz.js index 5d20a2d488a8d304c590b7d4d63d533db84fdcbf..63a41afc0543e0a31c5e4161536be3d73196486a 100644 --- a/assets/Model.vue_vue_type_script_setup_true_lang-DfGKadm0.js +++ b/assets/Model.vue_vue_type_script_setup_true_lang-CSqfK4Nz.js @@ -1 +1 @@ -import{n as F,T as Y,A as re,L as P,o as N,r as ue,D as se,I as de,m as O,M as ce,p as R}from"./live2d-zip-loader-BdiFCiUD.js";import{bM as ve,d as $,g as h,w as p,m as j,H as q,c as G,o as X,p as U,br as T,h as z,bC as pe,j as he,G as fe,s as me,v as ge,bN as Me,bO as we,bx as ye,a as be,q as Se}from"./index-rD0Uu1v9.js";const xe=o=>Math.max(0,Math.min(1,o||0)),C=o=>Math.round(xe(o)*255),Be=ve("rgb"),Ce=o=>{if(o===void 0)return;let l=C(o.r),t=C(o.g),d=C(o.b);return"#"+(1<<24|l<<16|t<<8|d).toString(16).slice(1)},Fe=o=>Ce(Be(o)),ke=$({__name:"Canvas",props:{width:null,height:null},setup(o,{expose:l}){const t=o,d=h(),e=h(),i=h();async function c(n){P.registerTicker(N),F.add(Y),e.value=new re({width:t.width,height:t.height,backgroundAlpha:0,preserveDrawingBuffer:!0}),i.value=e.value.view,i.value.style.objectFit="contain",n.appendChild(e.value.view)}function y(){var n;e.value&&e.value.renderer.resize(t.width,t.height),(n=e.value)!=null&&n.view&&(e.value.view.width=t.width,e.value.view.height=t.height)}p([()=>t.width,()=>t.height],()=>y()),j(async()=>d.value&&await c(d.value)),q(()=>{var n;return(n=e.value)==null?void 0:n.destroy()});async function B(){return new Promise(g=>{if(!i.value||!e.value)return g(null);e.value.render(),i.value.toBlob(g)})}return l({captureFrame:B}),(n,g)=>(X(),G("div",{ref_key:"containerRef",ref:d,"h-full":"","w-full":""},[U(n.$slots,"default",{app:e.value})],512))}});function V(o,l,t){return(1-t)*o+t*l}function H(o,l){return o+Math.random()*(l-o)}function Pe(){let o=-1,l,t=-1;function d(e,i){(i>=o||il.app),d=T(()=>l.paused),e=h(),i=h(0),c=h(0),y=z(()=>Math.max(0,Math.min(100,l.mouthOpenSize))),B=pe(),n=he(Se),g=z(()=>n.between("sm","md").value||n.smaller("sm").value),W=Pe(),I=fe(new se({alpha:.2,blur:0,distance:20,rotation:45}));function J(){return e.value.internalModel.coreModel}function D(a){if(!a.value)return;let r=2.2;g.value&&(r=2.2);const f=l.height*.95/c.value*r,s=l.width*.95/i.value*r,m=Math.min(f,s);a.value.scale.set(m,m)}const{live2dModelFile:b,loadingLive2dModel:M,live2dCurrentMotion:K,availableLive2dMotions:Q,live2dLoadSource:S,live2dModelUrl:k,themeColorsHue:Z,themeColorsHueDynamic:_}=me(ge()),ee=h({group:"Idle",index:0});async function ae(){var L;if(!t.value)return;e.value&&(t.value.stage.removeChild(e.value),e.value.destroy(),e.value=void 0);const a=new P;S.value==="file"?await R.setupLive2DModel(a,[b.value]):S.value==="url"&&await R.setupLive2DModel(a,k.value),e.value=a,t.value.stage.addChild(e.value),i.value=e.value.width,c.value=e.value.height,e.value.x=l.width/2,e.value.y=l.height,e.value.rotation=Math.PI,e.value.skew.x=Math.PI,e.value.anchor.set(.5,.5),D(e),e.value.on("hit",v=>{e.value&&v.includes("body")&&e.value.motion("tap_body")});const r=e.value.internalModel,f=r.coreModel,s=r.motionManager;f.setParameterValueById("ParamMouthOpenY",y.value),Q.value=Object.entries(s.definitions).flatMap(([v,u])=>u?u.map((ie,ne)=>({motionName:v,motionIndex:ne,fileName:ie.File})):[]).filter(Boolean),s.groups.idle&&((L=s.motionGroups[s.groups.idle])==null||L.forEach(v=>{v._motionData.curves.forEach(u=>{(u.id==="ParamEyeBallX"||u.id==="ParamEyeBallY")&&(u.id=`_${u.id}`)})}));const m=s.update;s.update=function(v,u){return m==null||m.call(this,v,u),s.state.currentGroup===s.groups.idle&&W.update(r,u),!0},s.on("motionStart",(v,u)=>{ee.value={group:v,index:u}}),b.value&&await O.setItem("live2dModel",b.value),M.value=!1}async function te(){if(!t.value)return;P.registerTicker(N),F.add(Y),F.add(de);const a=await O.getItem("live2dModel");if(a){b.value=a,S.value="file",M.value=!0;return}if(k.value){S.value="url",M.value=!0;return}M.value=!1}async function le(a,r){await e.value.motion(a,r,ce.FORCE)}const oe=Me(()=>{e.value&&(e.value.x=l.width/2,e.value.y=l.height,D(e))},100),A=h(),w=h(0);function x(){if(e.value){const a=getComputedStyle(A.value).backgroundColor;I.value.color=Number(Fe(a).replace("#","0x")),e.value.filters=[I.value]}}p([()=>l.width,()=>l.height],()=>oe()),p(B,x,{immediate:!0}),p([e,Z],x);function E(){x(),w.value=requestAnimationFrame(E)}return p(_,()=>{_.value?w.value=requestAnimationFrame(E):(cancelAnimationFrame(w.value),w.value=0)},{immediate:!0}),p(y,a=>J().setParameterValueById("ParamMouthOpenY",a)),p(t,te),p(K,a=>le(a.group,a.index)),p(d,a=>{var r,f;a?(r=t.value)==null||r.stop():(f=t.value)==null||f.start()}),we(M,a=>{a&&ae()},{debounce:1e3}),j(x),q(()=>{var a;cancelAnimationFrame(w.value),e.value&&((a=t.value)==null||a.stage.removeChild(e.value))}),(a,r)=>(X(),G(ye,null,[be("div",{ref_key:"dropShadowColorComputer",ref:A,hidden:"",bg:"primary-400 dark:primary-500"},null,512),U(a.$slots,"default")],64))}});export{_e as _,ke as a,H as r}; +import{n as F,T as Y,A as re,L as P,o as N,r as ue,D as se,I as de,m as O,M as ce,p as R}from"./live2d-zip-loader-C5j9stxV.js";import{bM as ve,d as $,g as h,w as p,m as j,H as q,c as G,o as X,p as U,br as T,h as z,bC as pe,j as he,G as fe,s as me,v as ge,bN as Me,bO as we,bx as ye,a as be,q as Se}from"./index-Dlp4W1Zl.js";const xe=o=>Math.max(0,Math.min(1,o||0)),C=o=>Math.round(xe(o)*255),Be=ve("rgb"),Ce=o=>{if(o===void 0)return;let l=C(o.r),t=C(o.g),d=C(o.b);return"#"+(1<<24|l<<16|t<<8|d).toString(16).slice(1)},Fe=o=>Ce(Be(o)),ke=$({__name:"Canvas",props:{width:null,height:null},setup(o,{expose:l}){const t=o,d=h(),e=h(),i=h();async function c(n){P.registerTicker(N),F.add(Y),e.value=new re({width:t.width,height:t.height,backgroundAlpha:0,preserveDrawingBuffer:!0}),i.value=e.value.view,i.value.style.objectFit="contain",n.appendChild(e.value.view)}function y(){var n;e.value&&e.value.renderer.resize(t.width,t.height),(n=e.value)!=null&&n.view&&(e.value.view.width=t.width,e.value.view.height=t.height)}p([()=>t.width,()=>t.height],()=>y()),j(async()=>d.value&&await c(d.value)),q(()=>{var n;return(n=e.value)==null?void 0:n.destroy()});async function B(){return new Promise(g=>{if(!i.value||!e.value)return g(null);e.value.render(),i.value.toBlob(g)})}return l({captureFrame:B}),(n,g)=>(X(),G("div",{ref_key:"containerRef",ref:d,"h-full":"","w-full":""},[U(n.$slots,"default",{app:e.value})],512))}});function V(o,l,t){return(1-t)*o+t*l}function H(o,l){return o+Math.random()*(l-o)}function Pe(){let o=-1,l,t=-1;function d(e,i){(i>=o||il.app),d=T(()=>l.paused),e=h(),i=h(0),c=h(0),y=z(()=>Math.max(0,Math.min(100,l.mouthOpenSize))),B=pe(),n=he(Se),g=z(()=>n.between("sm","md").value||n.smaller("sm").value),W=Pe(),I=fe(new se({alpha:.2,blur:0,distance:20,rotation:45}));function J(){return e.value.internalModel.coreModel}function D(a){if(!a.value)return;let r=2.2;g.value&&(r=2.2);const f=l.height*.95/c.value*r,s=l.width*.95/i.value*r,m=Math.min(f,s);a.value.scale.set(m,m)}const{live2dModelFile:b,loadingLive2dModel:M,live2dCurrentMotion:K,availableLive2dMotions:Q,live2dLoadSource:S,live2dModelUrl:k,themeColorsHue:Z,themeColorsHueDynamic:_}=me(ge()),ee=h({group:"Idle",index:0});async function ae(){var L;if(!t.value)return;e.value&&(t.value.stage.removeChild(e.value),e.value.destroy(),e.value=void 0);const a=new P;S.value==="file"?await R.setupLive2DModel(a,[b.value]):S.value==="url"&&await R.setupLive2DModel(a,k.value),e.value=a,t.value.stage.addChild(e.value),i.value=e.value.width,c.value=e.value.height,e.value.x=l.width/2,e.value.y=l.height,e.value.rotation=Math.PI,e.value.skew.x=Math.PI,e.value.anchor.set(.5,.5),D(e),e.value.on("hit",v=>{e.value&&v.includes("body")&&e.value.motion("tap_body")});const r=e.value.internalModel,f=r.coreModel,s=r.motionManager;f.setParameterValueById("ParamMouthOpenY",y.value),Q.value=Object.entries(s.definitions).flatMap(([v,u])=>u?u.map((ie,ne)=>({motionName:v,motionIndex:ne,fileName:ie.File})):[]).filter(Boolean),s.groups.idle&&((L=s.motionGroups[s.groups.idle])==null||L.forEach(v=>{v._motionData.curves.forEach(u=>{(u.id==="ParamEyeBallX"||u.id==="ParamEyeBallY")&&(u.id=`_${u.id}`)})}));const m=s.update;s.update=function(v,u){return m==null||m.call(this,v,u),s.state.currentGroup===s.groups.idle&&W.update(r,u),!0},s.on("motionStart",(v,u)=>{ee.value={group:v,index:u}}),b.value&&await O.setItem("live2dModel",b.value),M.value=!1}async function te(){if(!t.value)return;P.registerTicker(N),F.add(Y),F.add(de);const a=await O.getItem("live2dModel");if(a){b.value=a,S.value="file",M.value=!0;return}if(k.value){S.value="url",M.value=!0;return}M.value=!1}async function le(a,r){await e.value.motion(a,r,ce.FORCE)}const oe=Me(()=>{e.value&&(e.value.x=l.width/2,e.value.y=l.height,D(e))},100),A=h(),w=h(0);function x(){if(e.value){const a=getComputedStyle(A.value).backgroundColor;I.value.color=Number(Fe(a).replace("#","0x")),e.value.filters=[I.value]}}p([()=>l.width,()=>l.height],()=>oe()),p(B,x,{immediate:!0}),p([e,Z],x);function E(){x(),w.value=requestAnimationFrame(E)}return p(_,()=>{_.value?w.value=requestAnimationFrame(E):(cancelAnimationFrame(w.value),w.value=0)},{immediate:!0}),p(y,a=>J().setParameterValueById("ParamMouthOpenY",a)),p(t,te),p(K,a=>le(a.group,a.index)),p(d,a=>{var r,f;a?(r=t.value)==null||r.stop():(f=t.value)==null||f.start()}),we(M,a=>{a&&ae()},{debounce:1e3}),j(x),q(()=>{var a;cancelAnimationFrame(w.value),e.value&&((a=t.value)==null||a.stage.removeChild(e.value))}),(a,r)=>(X(),G(ye,null,[be("div",{ref_key:"dropShadowColorComputer",ref:A,hidden:"",bg:"primary-400 dark:primary-500"},null,512),U(a.$slots,"default")],64))}});export{_e as _,ke as a,H as r}; diff --git a/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js b/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js similarity index 84% rename from assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js rename to assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js index d3c569530cb8fa3b7ba24337eee1abb01c83597e..acb0334be9ce223c82c2b38e88f7b771576e6175 100644 --- a/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js +++ b/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js @@ -1 +1 @@ -import{_ as s}from"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import{d as n,bF as t,i as u,bG as p,h as m,x as c,o as f,e as b}from"./index-rD0Uu1v9.js";const y=n({__name:"ProviderApiKeyInput",props:t({providerName:null,placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const l=e,{t:a}=u(),o=p(e,"modelValue"),d=m(()=>l.description||`API Key for ${l.providerName}`);return(v,r)=>(f(),c(s,{modelValue:o.value,"onUpdate:modelValue":r[0]||(r[0]=i=>o.value=i),label:e.label||b(a)("settings.pages.providers.common.fields.field.api-key.label"),description:d.value,placeholder:e.placeholder,required:e.required,type:"password"},null,8,["modelValue","label","description","placeholder","required"]))}});export{y as _}; +import{_ as s}from"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import{d as n,bF as t,i as u,bG as p,h as m,x as c,o as f,e as b}from"./index-Dlp4W1Zl.js";const y=n({__name:"ProviderApiKeyInput",props:t({providerName:null,placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const l=e,{t:a}=u(),o=p(e,"modelValue"),d=m(()=>l.description||`API Key for ${l.providerName}`);return(v,r)=>(f(),c(s,{modelValue:o.value,"onUpdate:modelValue":r[0]||(r[0]=i=>o.value=i),label:e.label||b(a)("settings.pages.providers.common.fields.field.api-key.label"),description:d.value,placeholder:e.placeholder,required:e.required,type:"password"},null,8,["modelValue","label","description","placeholder","required"]))}});export{y as _}; diff --git a/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js b/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js similarity index 88% rename from assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js rename to assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js index 07d3ca4d01bb096d0e57e5a71f1fea68df2bb6fd..37f5d3ec545e39770a07b9944125275f9a85cd11 100644 --- a/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js +++ b/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js @@ -1 +1 @@ -import{_ as p}from"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import{d,g as m,x as u,o as c,y as n,a as e,p as f,D as _,z as v,bF as b,bG as g}from"./index-rD0Uu1v9.js";import{_ as V}from"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";const x=["onClick"],h={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},y={"mt-4":""},q=d({__name:"ProviderAdvancedSettings",props:{title:null,initialVisible:{type:Boolean}},setup(l){const a=m(l.initialVisible||!1);function r(){a.value=!a.value}return(o,i)=>(c(),u(p,{"w-full":""},{trigger:n(s=>[e("button",{transition:"all ease-in-out duration-250","w-full":"",flex:"","items-center":"","gap-1.5":"","outline-none":"",class:"[&_.provider-icon]:grayscale-100 [&_.provider-icon]:hover:grayscale-0",onClick:()=>s.setVisible(!s.visible)&&r()},[e("h2",h,[e("span",null,_(l.title||"Advanced"),1)]),e("div",{transform:"",transition:"transform duration-250",class:v({"rotate-180":s.visible})},i[0]||(i[0]=[e("div",{"i-solar:alt-arrow-down-bold-duotone":""},null,-1)]),2)],8,x)]),default:n(()=>[e("div",y,[f(o.$slots,"default")])]),_:3}))}}),w=d({__name:"ProviderBaseUrlInput",props:b({placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(l){const t=l,a=g(l,"modelValue");return(r,o)=>(c(),u(V,{modelValue:a.value,"onUpdate:modelValue":o[0]||(o[0]=i=>a.value=i),label:t.label||"Base URL",description:t.description||"Custom base URL (optional)",placeholder:t.placeholder,required:t.required,type:"text"},null,8,["modelValue","label","description","placeholder","required"]))}});export{q as _,w as a}; +import{_ as p}from"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import{d,g as m,x as u,o as c,y as n,a as e,p as f,D as _,z as v,bF as b,bG as g}from"./index-Dlp4W1Zl.js";import{_ as V}from"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";const x=["onClick"],h={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},y={"mt-4":""},q=d({__name:"ProviderAdvancedSettings",props:{title:null,initialVisible:{type:Boolean}},setup(l){const a=m(l.initialVisible||!1);function r(){a.value=!a.value}return(o,i)=>(c(),u(p,{"w-full":""},{trigger:n(s=>[e("button",{transition:"all ease-in-out duration-250","w-full":"",flex:"","items-center":"","gap-1.5":"","outline-none":"",class:"[&_.provider-icon]:grayscale-100 [&_.provider-icon]:hover:grayscale-0",onClick:()=>s.setVisible(!s.visible)&&r()},[e("h2",h,[e("span",null,_(l.title||"Advanced"),1)]),e("div",{transform:"",transition:"transform duration-250",class:v({"rotate-180":s.visible})},i[0]||(i[0]=[e("div",{"i-solar:alt-arrow-down-bold-duotone":""},null,-1)]),2)],8,x)]),default:n(()=>[e("div",y,[f(o.$slots,"default")])]),_:3}))}}),w=d({__name:"ProviderBaseUrlInput",props:b({placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(l){const t=l,a=g(l,"modelValue");return(r,o)=>(c(),u(V,{modelValue:a.value,"onUpdate:modelValue":o[0]||(o[0]=i=>a.value=i),label:t.label||"Base URL",description:t.description||"Custom base URL (optional)",placeholder:t.placeholder,required:t.required,type:"text"},null,8,["modelValue","label","description","placeholder","required"]))}});export{q as _,w as a}; diff --git a/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js b/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js similarity index 94% rename from assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js rename to assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js index f80e51f0edc6236e2e75360ffda4e736bbb31752..8e56a8dc47018bde22f246f55f68f2cc2038c347 100644 --- a/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js +++ b/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js @@ -1 +1 @@ -import{d as o,c as s,o as a,a as e,p as i,C as u,D as l}from"./index-rD0Uu1v9.js";const c={flex:"~ col gap-6"},x={flex:"~ row","items-center":"","justify-between":""},f={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},p={text:"neutral-400 dark:neutral-500"},g=o({__name:"ProviderBasicSettings",props:{title:null,description:null,onReset:{type:Function}},setup(t){return(r,n)=>(a(),s("div",c,[e("div",x,[e("div",null,[e("h2",f,l(t.title||"Basic"),1),e("div",p,[e("span",null,l(t.description||"Essential settings"),1)])]),t.onReset?(a(),s("button",{key:0,title:"Reset settings",flex:"","items-center":"","justify-center":"","rounded-full":"","p-2":"",transition:"all duration-250 ease-in-out",text:"neutral-500 dark:neutral-400",bg:"transparent dark:transparent hover:neutral-200 dark:hover:neutral-800 active:neutral-300 dark:active:neutral-700",onClick:n[0]||(n[0]=(...d)=>t.onReset&&t.onReset(...d))},n[1]||(n[1]=[e("div",{"i-solar:refresh-bold-duotone":"","text-xl":""},null,-1)]))):u("",!0)]),i(r.$slots,"default")]))}}),m={bg:"neutral-50 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-6"},k=o({__name:"ProviderSettingsContainer",setup(t){return(r,n)=>(a(),s("div",m,[i(r.$slots,"default")]))}});export{k as _,g as a}; +import{d as o,c as s,o as a,a as e,p as i,C as u,D as l}from"./index-Dlp4W1Zl.js";const c={flex:"~ col gap-6"},x={flex:"~ row","items-center":"","justify-between":""},f={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},p={text:"neutral-400 dark:neutral-500"},g=o({__name:"ProviderBasicSettings",props:{title:null,description:null,onReset:{type:Function}},setup(t){return(r,n)=>(a(),s("div",c,[e("div",x,[e("div",null,[e("h2",f,l(t.title||"Basic"),1),e("div",p,[e("span",null,l(t.description||"Essential settings"),1)])]),t.onReset?(a(),s("button",{key:0,title:"Reset settings",flex:"","items-center":"","justify-center":"","rounded-full":"","p-2":"",transition:"all duration-250 ease-in-out",text:"neutral-500 dark:neutral-400",bg:"transparent dark:transparent hover:neutral-200 dark:hover:neutral-800 active:neutral-300 dark:active:neutral-700",onClick:n[0]||(n[0]=(...d)=>t.onReset&&t.onReset(...d))},n[1]||(n[1]=[e("div",{"i-solar:refresh-bold-duotone":"","text-xl":""},null,-1)]))):u("",!0)]),i(r.$slots,"default")]))}}),m={bg:"neutral-50 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-6"},k=o({__name:"ProviderSettingsContainer",setup(t){return(r,n)=>(a(),s("div",m,[i(r.$slots,"default")]))}});export{k as _,g as a}; diff --git a/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js b/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js similarity index 94% rename from assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js rename to assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js index 8f9dae7848fab1281d60ad018ef9cc5f22f4ff51..1de1c74cef3c0a9d15eb70a705a17c8154be5657 100644 --- a/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js +++ b/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js @@ -1 +1 @@ -import{d as s,bw as d,c as n,o as r,A as v,p as u,a as t,D as c,z as p,bx as x}from"./index-rD0Uu1v9.js";const m={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},f={relative:""},k={"text-nowrap":"","text-3xl":"","font-semibold":""},y={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},w=s({__name:"ProviderSettingsLayout",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function}},setup(o){return(a,e)=>{const i=d("motion");return r(),n(x,null,[v((r(),n("div",m,[t("button",{onClick:e[0]||(e[0]=(...l)=>o.onBack&&o.onBack(...l))},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",f,[e[2]||(e[2]=t("div",{absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},[t("span",{text:"neutral-300 dark:neutral-500","text-nowrap":""},"Provider")],-1)),t("div",k,c(o.providerName),1)])])),[[i]]),u(a.$slots,"default"),t("div",y,[t("div",{text:"40",class:p(o.providerIcon||o.providerIconColor)},null,2)])],64)}}});export{w as _}; +import{d as s,bw as d,c as n,o as r,A as v,p as u,a as t,D as c,z as p,bx as x}from"./index-Dlp4W1Zl.js";const m={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},f={relative:""},k={"text-nowrap":"","text-3xl":"","font-semibold":""},y={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},w=s({__name:"ProviderSettingsLayout",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function}},setup(o){return(a,e)=>{const i=d("motion");return r(),n(x,null,[v((r(),n("div",m,[t("button",{onClick:e[0]||(e[0]=(...l)=>o.onBack&&o.onBack(...l))},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",f,[e[2]||(e[2]=t("div",{absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},[t("span",{text:"neutral-300 dark:neutral-500","text-nowrap":""},"Provider")],-1)),t("div",k,c(o.providerName),1)])])),[[i]]),u(a.$slots,"default"),t("div",y,[t("div",{text:"40",class:p(o.providerIcon||o.providerIconColor)},null,2)])],64)}}});export{w as _}; diff --git a/assets/RadioCardDetailManySelect-cGsz75Pf.js b/assets/RadioCardDetailManySelect-rPQeY4V8.js similarity index 98% rename from assets/RadioCardDetailManySelect-cGsz75Pf.js rename to assets/RadioCardDetailManySelect-rPQeY4V8.js index d7fb04e9654873cf8812277fb372106540c7524f..0386f6b92d0ff02dd99d6834591e27ad2b340c08 100644 --- a/assets/RadioCardDetailManySelect-cGsz75Pf.js +++ b/assets/RadioCardDetailManySelect-rPQeY4V8.js @@ -1 +1 @@ -import{d as g,bF as f,bG as w,g as b,c as n,o as d,z as o,A as V,a as t,bA as B,C as v,D as c,b as $,y as S,c0 as k,bn as C,h as T,bJ as M,bx as z,by as D,x as N}from"./index-rD0Uu1v9.js";import{_ as E}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import{_ as P}from"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const U=["checked","name","value"],q={class:"relative mr-3 mt-0.5 flex-shrink-0"},L={class:"w-full flex flex-col gap-2"},j={class:"flex items-center"},A={key:0,class:"relative"},F=["title"],G={key:1,class:"mt-2"},J=g({__name:"RadioCardDetail",props:f({id:null,name:null,value:null,title:null,description:null,deprecated:{type:Boolean,default:!1},showExpandCollapse:{type:Boolean,default:!0},expandCollapseThreshold:{default:100},customInputValue:{default:""},customInputPlaceholder:{default:""},showCustomInput:{type:Boolean,default:!1}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const a=w(e,"modelValue"),m=b(!1);function i(){m.value=!m.value}return(x,r)=>(d(),n("label",{key:e.id,class:o(["form_radio-card-detail relative flex cursor-pointer items-start rounded-xl p-3 pr-[20px]",[a.value===e.value?"bg-primary-50 dark:bg-primary-900/20 border-primary-100 dark:border-primary-900 hover:border-primary-500/30 dark:hover:border-primary-400/30":"bg-white dark:bg-neutral-900/20 border-neutral-100 dark:border-neutral-900 hover:border-primary-500/30 dark:hover:border-primary-400/30",a.value===e.value?"form_radio-card-detail-active":"",e.deprecated?"opacity-60":""]]),transition:"all duration-200 ease-in-out",border:"2 solid"},[V(t("input",{"onUpdate:modelValue":r[0]||(r[0]=s=>a.value=s),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"absolute opacity-0"},null,8,U),[[B,a.value]]),t("div",q,[t("div",{class:o(["size-5 border-2 rounded-full transition-colors duration-200",[a.value===e.value?"border-primary-500 dark:border-primary-400":"border-neutral-300 dark:border-neutral-600"]])},[t("div",{class:o(["absolute left-1/2 top-1/2 size-3 rounded-full transition-opacity duration-200 -translate-x-1/2 -translate-y-1/2",[a.value===e.value?"opacity-100 bg-primary-500 dark:bg-primary-400":"opacity-0"]])},null,2)],2)]),t("div",L,[t("div",j,[t("span",{class:o(["line-clamp-1 font-medium",[a.value===e.value?"text-neutral-700 dark:text-neutral-300":"text-neutral-700 dark:text-neutral-400"]])},c(e.title),3)]),e.description?(d(),n("div",A,[$(E,null,{default:S(()=>[m.value?(d(),n("div",{key:1,class:o(["cursor-pointer text-xs",[a.value===e.value?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]]),onClick:k(i,["prevent"])},c(e.description),3)):(d(),n("div",{key:0,class:o(["line-clamp-2 cursor-pointer text-xs",[a.value===e.value?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]]),title:e.description,onClick:k(i,["prevent"])},c(e.description),11,F))]),_:1}),e.showExpandCollapse&&e.description.length>e.expandCollapseThreshold?(d(),n("button",{key:0,class:"text-primary-500 dark:text-primary-600 mt-0.5 inline-flex items-center text-xs",onClick:k(i,["prevent"])},[t("span",null,c(m.value?"Show less":"Show more"),1),t("div",{class:o([{"rotate-180":m.value},"transition-transform duration-200"])},r[2]||(r[2]=[t("div",{"i-solar:alt-arrow-down-bold-duotone":"","ml-0.5":"","text-xs":""},null,-1)]),2)])):v("",!0)])):v("",!0),e.showCustomInput&&a.value===e.value?(d(),n("div",G,[$(P,{modelValue:a.value,"onUpdate:modelValue":r[1]||(r[1]=s=>a.value=s),type:"text",class:"w-full border border-neutral-300 rounded bg-white px-2 py-1 text-sm dark:border-neutral-700 dark:bg-neutral-900",placeholder:e.customInputPlaceholder},null,8,["modelValue","placeholder"])])):v("",!0)])],2))}}),Q=C(J,[["__scopeId","data-v-1629f300"]]),H=["checked","name","value"],K={flex:"~ col","min-h-16":"","w-full":"","items-start":"","justify-center":"","pb-2":"","pl-5":"","pr-4":"","pt-2":""},O=g({__name:"RadioCardSimple",props:f({id:null,name:null,value:null,title:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const a=w(e,"modelValue");return(m,i)=>(d(),n("label",{key:e.id,border:"2px solid",class:o(["form_radio-card-simple relative",[a.value===e.value?"bg-primary-50 dark:bg-primary-900/20 border-primary-100 dark:border-primary-900 hover:border-primary-500/30 dark:hover:border-primary-400/30":"bg-white dark:bg-neutral-900/20 border-neutral-100 dark:border-neutral-900 hover:border-primary-500/30 dark:hover:border-primary-400/30",a.value===e.value?"form_radio-card-simple-active":""]]),transition:"all duration-200 ease-in-out",flex:"~ col",block:"","min-w-50":"","w-fit":"","cursor-pointer":"","items-start":"","rounded-xl":"","p-4":"","text-left":""},[V(t("input",{"onUpdate:modelValue":i[0]||(i[0]=x=>a.value=x),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"[&:checked+div]:border-primary-500 dark:[&:checked+div]:border-primary-400 absolute opacity-0 [&:checked+div_.radio-dot]:opacity-100"},null,8,H),[[B,a.value]]),i[1]||(i[1]=t("div",{class:"radio-circle absolute left-2 top-2 size-5 rounded-full",border:"2 solid neutral-300 dark:neutral-600",transition:"all duration-200 ease-in-out"},[t("div",{class:"radio-dot absolute left-1/2 top-1/2 size-3 rounded-full opacity-0 -translate-x-1/2 -translate-y-1/2",transition:"all duration-200 ease-in-out",bg:"primary-500 dark:primary-400"})],-1)),t("div",K,[t("span",{class:o(["radio-item-name font-bold",[a.value===e.value?"text-neutral-700 dark:text-neutral-300":"text-neutral-500 dark:text-neutral-500"]]),text:"md",transition:"all duration-200 ease-in-out"},c(e.title),3),e.description?(d(),n("span",{key:0,class:o(["radio-item-description",[a.value===e.value?"text-neutral-600 dark:text-neutral-400":"text-neutral-400 dark:text-neutral-600"]]),transition:"all duration-200 ease-in-out"},c(e.description),3)):v("",!0)]),i[2]||(i[2]=t("div",{class:"bg-dotted-neutral-200/80 dark:bg-dotted-neutral-700/50 [input:checked~&]:bg-dotted-primary-300/50 dark:[input:checked~&]:bg-dotted-primary-200/20",absolute:"","inset-0":"","z--1":"",style:{"background-size":"10px 10px","mask-image":"linear-gradient(165deg, white 30%, transparent 50%)"}},null,-1))],2))}}),se=C(O,[["__scopeId","data-v-dd41bc0b"]]),W={class:"radio-card-detail-many-select"},X={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},Y=["placeholder"],Z={class:"mt-4 space-y-2"},_={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},ee={key:1,class:"flex items-center gap-3 border border-2 border-amber-200 rounded-xl bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},te={class:"flex flex-col"},ae={class:"font-medium"},le={class:"text-sm text-amber-600 dark:text-amber-400"},re={class:"relative"},oe=g({__name:"RadioCardDetailManySelect",props:f({items:null,searchable:{type:Boolean,default:!0},searchPlaceholder:{default:"Search..."},searchNoResultsTitle:{default:"No results found"},searchNoResultsDescription:{default:"Try a different search term"},searchResultsText:{default:"{count} of {total} results"},customInputPlaceholder:{default:"Enter custom value"},expandButtonText:{default:"Show more"},collapseButtonText:{default:"Show less"}},{modelValue:{required:!0},modelModifiers:{}}),emits:f(["update:customValue"],["update:modelValue"]),setup(e,{emit:a}){const m=e,i=a,x=w(e,"modelValue"),r=b(""),s=b(!1),R=b(""),y=T(()=>{if(!r.value)return m.items;const p=r.value.toLowerCase();return m.items.filter(l=>l.name.toLowerCase().includes(p)||l.description&&l.description.toLowerCase().includes(p))});function I(p){R.value=p,i("update:customValue",p)}return(p,l)=>(d(),n("div",W,[e.searchable?(d(),n("div",X,[l[4]||(l[4]=t("div",{class:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"},[t("div",{"i-solar:magnifer-line-duotone":"",class:"text-neutral-500 dark:text-neutral-400"})],-1)),V(t("input",{"onUpdate:modelValue":l[0]||(l[0]=u=>r.value=u),type:"search",class:"w-full rounded-xl p-2.5 pl-10 text-sm outline-none",border:"focus:primary-100 dark:focus:primary-400/50 2 solid neutral-200 dark:neutral-800",transition:"all duration-200 ease-in-out",bg:"white dark:neutral-900",placeholder:e.searchPlaceholder},null,8,Y),[[M,r.value]])])):v("",!0),t("div",Z,[r.value?(d(),n("div",_,c(e.searchResultsText.replace("{count}",y.value.length.toString()).replace("{total}",e.items.length.toString())),1)):v("",!0),r.value&&y.value.length===0?(d(),n("div",ee,[l[5]||(l[5]=t("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),t("div",te,[t("span",ae,c(e.searchNoResultsTitle),1),t("span",le,c(e.searchNoResultsDescription.replace("{query}",r.value)),1)])])):v("",!0),t("div",re,[t("div",{class:o(["scrollbar-hide grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto pb-4",[s.value?"grid-cols-1 md:grid-cols-2 grid-flow-row auto-cols-auto":""]]),transition:"all duration-200 ease-in-out",style:{"scroll-snap-type":"x mandatory"}},[(d(!0),n(z,null,D(y.value,u=>(d(),N(Q,{id:u.id,key:u.id,modelValue:x.value,"onUpdate:modelValue":l[1]||(l[1]=h=>x.value=h),value:u.id,title:u.name,description:u.description,deprecated:u.deprecated,"show-expand-collapse":!0,"expand-collapse-threshold":100,"show-custom-input":u.customizable,"custom-input-value":R.value,"custom-input-placeholder":e.customInputPlaceholder,name:"radio-card-detail-many-select",class:"scroll-snap-align-start","onUpdate:customInputValue":l[2]||(l[2]=h=>I(h))},null,8,["id","modelValue","value","title","description","deprecated","show-custom-input","custom-input-value","custom-input-placeholder"]))),128))],2),t("div",{bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"",class:o([s.value?"w-full":"mt-4 w-full rounded-lg"])},[t("button",{"w-full":"",flex:"","items-center":"","justify-center":"","gap-2":"","rounded-lg":"","py-2":"",transition:"all duration-200 ease-in-out",class:o([s.value?"bg-primary-500 hover:bg-primary-600 text-white":"bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800"]),onClick:l[3]||(l[3]=u=>s.value=!s.value)},[t("span",null,c(s.value?e.collapseButtonText:e.expandButtonText),1),t("div",{class:o([s.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),ue=C(oe,[["__scopeId","data-v-cd8353a6"]]);export{ue as R,se as a}; +import{d as g,bF as f,bG as w,g as b,c as n,o as d,z as o,A as V,a as t,bA as B,C as v,D as c,b as $,y as S,c0 as k,bn as C,h as T,bJ as M,bx as z,by as D,x as N}from"./index-Dlp4W1Zl.js";import{_ as E}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import{_ as P}from"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const U=["checked","name","value"],q={class:"relative mr-3 mt-0.5 flex-shrink-0"},L={class:"w-full flex flex-col gap-2"},j={class:"flex items-center"},A={key:0,class:"relative"},F=["title"],G={key:1,class:"mt-2"},J=g({__name:"RadioCardDetail",props:f({id:null,name:null,value:null,title:null,description:null,deprecated:{type:Boolean,default:!1},showExpandCollapse:{type:Boolean,default:!0},expandCollapseThreshold:{default:100},customInputValue:{default:""},customInputPlaceholder:{default:""},showCustomInput:{type:Boolean,default:!1}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const a=w(e,"modelValue"),m=b(!1);function i(){m.value=!m.value}return(x,r)=>(d(),n("label",{key:e.id,class:o(["form_radio-card-detail relative flex cursor-pointer items-start rounded-xl p-3 pr-[20px]",[a.value===e.value?"bg-primary-50 dark:bg-primary-900/20 border-primary-100 dark:border-primary-900 hover:border-primary-500/30 dark:hover:border-primary-400/30":"bg-white dark:bg-neutral-900/20 border-neutral-100 dark:border-neutral-900 hover:border-primary-500/30 dark:hover:border-primary-400/30",a.value===e.value?"form_radio-card-detail-active":"",e.deprecated?"opacity-60":""]]),transition:"all duration-200 ease-in-out",border:"2 solid"},[V(t("input",{"onUpdate:modelValue":r[0]||(r[0]=s=>a.value=s),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"absolute opacity-0"},null,8,U),[[B,a.value]]),t("div",q,[t("div",{class:o(["size-5 border-2 rounded-full transition-colors duration-200",[a.value===e.value?"border-primary-500 dark:border-primary-400":"border-neutral-300 dark:border-neutral-600"]])},[t("div",{class:o(["absolute left-1/2 top-1/2 size-3 rounded-full transition-opacity duration-200 -translate-x-1/2 -translate-y-1/2",[a.value===e.value?"opacity-100 bg-primary-500 dark:bg-primary-400":"opacity-0"]])},null,2)],2)]),t("div",L,[t("div",j,[t("span",{class:o(["line-clamp-1 font-medium",[a.value===e.value?"text-neutral-700 dark:text-neutral-300":"text-neutral-700 dark:text-neutral-400"]])},c(e.title),3)]),e.description?(d(),n("div",A,[$(E,null,{default:S(()=>[m.value?(d(),n("div",{key:1,class:o(["cursor-pointer text-xs",[a.value===e.value?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]]),onClick:k(i,["prevent"])},c(e.description),3)):(d(),n("div",{key:0,class:o(["line-clamp-2 cursor-pointer text-xs",[a.value===e.value?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]]),title:e.description,onClick:k(i,["prevent"])},c(e.description),11,F))]),_:1}),e.showExpandCollapse&&e.description.length>e.expandCollapseThreshold?(d(),n("button",{key:0,class:"text-primary-500 dark:text-primary-600 mt-0.5 inline-flex items-center text-xs",onClick:k(i,["prevent"])},[t("span",null,c(m.value?"Show less":"Show more"),1),t("div",{class:o([{"rotate-180":m.value},"transition-transform duration-200"])},r[2]||(r[2]=[t("div",{"i-solar:alt-arrow-down-bold-duotone":"","ml-0.5":"","text-xs":""},null,-1)]),2)])):v("",!0)])):v("",!0),e.showCustomInput&&a.value===e.value?(d(),n("div",G,[$(P,{modelValue:a.value,"onUpdate:modelValue":r[1]||(r[1]=s=>a.value=s),type:"text",class:"w-full border border-neutral-300 rounded bg-white px-2 py-1 text-sm dark:border-neutral-700 dark:bg-neutral-900",placeholder:e.customInputPlaceholder},null,8,["modelValue","placeholder"])])):v("",!0)])],2))}}),Q=C(J,[["__scopeId","data-v-1629f300"]]),H=["checked","name","value"],K={flex:"~ col","min-h-16":"","w-full":"","items-start":"","justify-center":"","pb-2":"","pl-5":"","pr-4":"","pt-2":""},O=g({__name:"RadioCardSimple",props:f({id:null,name:null,value:null,title:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const a=w(e,"modelValue");return(m,i)=>(d(),n("label",{key:e.id,border:"2px solid",class:o(["form_radio-card-simple relative",[a.value===e.value?"bg-primary-50 dark:bg-primary-900/20 border-primary-100 dark:border-primary-900 hover:border-primary-500/30 dark:hover:border-primary-400/30":"bg-white dark:bg-neutral-900/20 border-neutral-100 dark:border-neutral-900 hover:border-primary-500/30 dark:hover:border-primary-400/30",a.value===e.value?"form_radio-card-simple-active":""]]),transition:"all duration-200 ease-in-out",flex:"~ col",block:"","min-w-50":"","w-fit":"","cursor-pointer":"","items-start":"","rounded-xl":"","p-4":"","text-left":""},[V(t("input",{"onUpdate:modelValue":i[0]||(i[0]=x=>a.value=x),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"[&:checked+div]:border-primary-500 dark:[&:checked+div]:border-primary-400 absolute opacity-0 [&:checked+div_.radio-dot]:opacity-100"},null,8,H),[[B,a.value]]),i[1]||(i[1]=t("div",{class:"radio-circle absolute left-2 top-2 size-5 rounded-full",border:"2 solid neutral-300 dark:neutral-600",transition:"all duration-200 ease-in-out"},[t("div",{class:"radio-dot absolute left-1/2 top-1/2 size-3 rounded-full opacity-0 -translate-x-1/2 -translate-y-1/2",transition:"all duration-200 ease-in-out",bg:"primary-500 dark:primary-400"})],-1)),t("div",K,[t("span",{class:o(["radio-item-name font-bold",[a.value===e.value?"text-neutral-700 dark:text-neutral-300":"text-neutral-500 dark:text-neutral-500"]]),text:"md",transition:"all duration-200 ease-in-out"},c(e.title),3),e.description?(d(),n("span",{key:0,class:o(["radio-item-description",[a.value===e.value?"text-neutral-600 dark:text-neutral-400":"text-neutral-400 dark:text-neutral-600"]]),transition:"all duration-200 ease-in-out"},c(e.description),3)):v("",!0)]),i[2]||(i[2]=t("div",{class:"bg-dotted-neutral-200/80 dark:bg-dotted-neutral-700/50 [input:checked~&]:bg-dotted-primary-300/50 dark:[input:checked~&]:bg-dotted-primary-200/20",absolute:"","inset-0":"","z--1":"",style:{"background-size":"10px 10px","mask-image":"linear-gradient(165deg, white 30%, transparent 50%)"}},null,-1))],2))}}),se=C(O,[["__scopeId","data-v-dd41bc0b"]]),W={class:"radio-card-detail-many-select"},X={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},Y=["placeholder"],Z={class:"mt-4 space-y-2"},_={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},ee={key:1,class:"flex items-center gap-3 border border-2 border-amber-200 rounded-xl bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},te={class:"flex flex-col"},ae={class:"font-medium"},le={class:"text-sm text-amber-600 dark:text-amber-400"},re={class:"relative"},oe=g({__name:"RadioCardDetailManySelect",props:f({items:null,searchable:{type:Boolean,default:!0},searchPlaceholder:{default:"Search..."},searchNoResultsTitle:{default:"No results found"},searchNoResultsDescription:{default:"Try a different search term"},searchResultsText:{default:"{count} of {total} results"},customInputPlaceholder:{default:"Enter custom value"},expandButtonText:{default:"Show more"},collapseButtonText:{default:"Show less"}},{modelValue:{required:!0},modelModifiers:{}}),emits:f(["update:customValue"],["update:modelValue"]),setup(e,{emit:a}){const m=e,i=a,x=w(e,"modelValue"),r=b(""),s=b(!1),R=b(""),y=T(()=>{if(!r.value)return m.items;const p=r.value.toLowerCase();return m.items.filter(l=>l.name.toLowerCase().includes(p)||l.description&&l.description.toLowerCase().includes(p))});function I(p){R.value=p,i("update:customValue",p)}return(p,l)=>(d(),n("div",W,[e.searchable?(d(),n("div",X,[l[4]||(l[4]=t("div",{class:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"},[t("div",{"i-solar:magnifer-line-duotone":"",class:"text-neutral-500 dark:text-neutral-400"})],-1)),V(t("input",{"onUpdate:modelValue":l[0]||(l[0]=u=>r.value=u),type:"search",class:"w-full rounded-xl p-2.5 pl-10 text-sm outline-none",border:"focus:primary-100 dark:focus:primary-400/50 2 solid neutral-200 dark:neutral-800",transition:"all duration-200 ease-in-out",bg:"white dark:neutral-900",placeholder:e.searchPlaceholder},null,8,Y),[[M,r.value]])])):v("",!0),t("div",Z,[r.value?(d(),n("div",_,c(e.searchResultsText.replace("{count}",y.value.length.toString()).replace("{total}",e.items.length.toString())),1)):v("",!0),r.value&&y.value.length===0?(d(),n("div",ee,[l[5]||(l[5]=t("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),t("div",te,[t("span",ae,c(e.searchNoResultsTitle),1),t("span",le,c(e.searchNoResultsDescription.replace("{query}",r.value)),1)])])):v("",!0),t("div",re,[t("div",{class:o(["scrollbar-hide grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto pb-4",[s.value?"grid-cols-1 md:grid-cols-2 grid-flow-row auto-cols-auto":""]]),transition:"all duration-200 ease-in-out",style:{"scroll-snap-type":"x mandatory"}},[(d(!0),n(z,null,D(y.value,u=>(d(),N(Q,{id:u.id,key:u.id,modelValue:x.value,"onUpdate:modelValue":l[1]||(l[1]=h=>x.value=h),value:u.id,title:u.name,description:u.description,deprecated:u.deprecated,"show-expand-collapse":!0,"expand-collapse-threshold":100,"show-custom-input":u.customizable,"custom-input-value":R.value,"custom-input-placeholder":e.customInputPlaceholder,name:"radio-card-detail-many-select",class:"scroll-snap-align-start","onUpdate:customInputValue":l[2]||(l[2]=h=>I(h))},null,8,["id","modelValue","value","title","description","deprecated","show-custom-input","custom-input-value","custom-input-placeholder"]))),128))],2),t("div",{bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"",class:o([s.value?"w-full":"mt-4 w-full rounded-lg"])},[t("button",{"w-full":"",flex:"","items-center":"","justify-center":"","gap-2":"","rounded-lg":"","py-2":"",transition:"all duration-200 ease-in-out",class:o([s.value?"bg-primary-500 hover:bg-primary-600 text-white":"bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800"]),onClick:l[3]||(l[3]=u=>s.value=!s.value)},[t("span",null,c(s.value?e.collapseButtonText:e.expandButtonText),1),t("div",{class:o([s.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),ue=C(oe,[["__scopeId","data-v-cd8353a6"]]);export{ue as R,se as a}; diff --git a/assets/Section.vue_vue_type_script_setup_true_lang-BtOV76U1.js b/assets/Section.vue_vue_type_script_setup_true_lang-Ju8FFDso.js similarity index 99% rename from assets/Section.vue_vue_type_script_setup_true_lang-BtOV76U1.js rename to assets/Section.vue_vue_type_script_setup_true_lang-Ju8FFDso.js index b3a13ea3486126e169869963b0d51f4fe16a9471..f8f17155ff52e2801481f67f34e3e777081b2daf 100644 --- a/assets/Section.vue_vue_type_script_setup_true_lang-BtOV76U1.js +++ b/assets/Section.vue_vue_type_script_setup_true_lang-Ju8FFDso.js @@ -1,3 +1,3 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{h as O,g as P,G as ht,w as K,ah as gt,ai as yt,bP as de,e as w,d as _,x as M,o as $,y as D,p as B,m as $e,b as Y,bQ as se,bR as jt,bS as wt,bT as bt,bU as Ut,E as xt,bV as he,bW as Yt,bv as Be,bX as Ct,bY as st,bZ as Pe,af as Q,C as Ot,b_ as Kt,ab as Xt,b$ as At,bH as Xe,D as Ge,c0 as Gt,c as De,n as Le,c1 as qt,br as Jt,c2 as Et,c3 as Qt,c4 as Zt,c5 as en,c6 as tn,H as nn,bx as Pt,a as fe,c7 as on,c8 as rn,c9 as ln,v as sn,by as an,z as Te,ca as un}from"./index-rD0Uu1v9.js";import{_ as cn}from"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";const dn=["top","right","bottom","left"],ie=Math.min,H=Math.max,_e=Math.round,Ae=Math.floor,X=e=>({x:e,y:e}),fn={left:"right",right:"left",bottom:"top",top:"bottom"},pn={start:"end",end:"start"};function ze(e,t,n){return H(e,ie(t,n))}function Z(e,t){return typeof e=="function"?e(t):e}function ee(e){return e.split("-")[0]}function ge(e){return e.split("-")[1]}function qe(e){return e==="x"?"y":"x"}function Je(e){return e==="y"?"height":"width"}function re(e){return["top","bottom"].includes(ee(e))?"y":"x"}function Qe(e){return qe(re(e))}function vn(e,t,n){n===void 0&&(n=!1);const o=ge(e),i=Qe(e),r=Je(i);let l=i==="x"?o===(n?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[r]>t.floating[r]&&(l=Re(l)),[l,Re(l)]}function mn(e){const t=Re(e);return[Ve(e),t,Ve(t)]}function Ve(e){return e.replace(/start|end/g,t=>pn[t])}function hn(e,t,n){const o=["left","right"],i=["right","left"],r=["top","bottom"],l=["bottom","top"];switch(e){case"top":case"bottom":return n?t?i:o:t?o:i;case"left":case"right":return t?r:l;default:return[]}}function gn(e,t,n,o){const i=ge(e);let r=hn(ee(e),n==="start",o);return i&&(r=r.map(l=>l+"-"+i),t&&(r=r.concat(r.map(Ve)))),r}function Re(e){return e.replace(/left|right|bottom|top/g,t=>fn[t])}function yn(e){return{top:0,right:0,bottom:0,left:0,...e}}function Tt(e){return typeof e!="number"?yn(e):{top:e,right:e,bottom:e,left:e}}function Se(e){const{x:t,y:n,width:o,height:i}=e;return{width:o,height:i,top:n,left:t,right:t+o,bottom:n+i,x:t,y:n}}function at(e,t,n){let{reference:o,floating:i}=e;const r=re(t),l=Qe(t),s=Je(l),u=ee(t),d=r==="y",a=o.x+o.width/2-i.width/2,c=o.y+o.height/2-i.height/2,v=o[s]/2-i[s]/2;let f;switch(u){case"top":f={x:a,y:o.y-i.height};break;case"bottom":f={x:a,y:o.y+o.height};break;case"right":f={x:o.x+o.width,y:c};break;case"left":f={x:o.x-i.width,y:c};break;default:f={x:o.x,y:o.y}}switch(ge(t)){case"start":f[l]-=v*(n&&d?-1:1);break;case"end":f[l]+=v*(n&&d?-1:1);break}return f}const wn=async(e,t,n)=>{const{placement:o="bottom",strategy:i="absolute",middleware:r=[],platform:l}=n,s=r.filter(Boolean),u=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:e,floating:t,strategy:i}),{x:a,y:c}=at(d,o,u),v=o,f={},p=0;for(let g=0;g({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:i,rects:r,platform:l,elements:s,middlewareData:u}=t,{element:d,padding:a=0}=Z(e,t)||{};if(d==null)return{};const c=Tt(a),v={x:n,y:o},f=Qe(i),p=Je(f),g=await l.getDimensions(d),m=f==="y",h=m?"top":"left",b=m?"bottom":"right",y=m?"clientHeight":"clientWidth",C=r.reference[p]+r.reference[f]-v[f]-r.floating[p],x=v[f]-r.reference[f],T=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let A=T?T[y]:0;(!A||!await(l.isElement==null?void 0:l.isElement(T)))&&(A=s.floating[y]||r.floating[p]);const R=C/2-x/2,L=A/2-g[p]/2-1,E=ie(c[h],L),z=ie(c[b],L),k=E,F=A-g[p]-z,S=A/2-g[p]/2+R,te=ze(k,S,F),N=!u.arrow&&ge(i)!=null&&S!==te&&r.reference[p]/2-(SS<=0)){var z,k;const S=(((z=r.flip)==null?void 0:z.index)||0)+1,te=A[S];if(te)return{data:{index:S,overflows:E},reset:{placement:te}};let N=(k=E.filter(U=>U.overflows[0]<=0).sort((U,ne)=>U.overflows[1]-ne.overflows[1])[0])==null?void 0:k.placement;if(!N)switch(f){case"bestFit":{var F;const U=(F=E.filter(ne=>{if(T){const oe=re(ne.placement);return oe===b||oe==="y"}return!0}).map(ne=>[ne.placement,ne.overflows.filter(oe=>oe>0).reduce((oe,Vt)=>oe+Vt,0)]).sort((ne,oe)=>ne[1]-oe[1])[0])==null?void 0:F[0];U&&(N=U);break}case"initialPlacement":N=s;break}if(i!==N)return{reset:{placement:N}}}return{}}}};function ut(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function ct(e){return dn.some(t=>e[t]>=0)}const Cn=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:o="referenceHidden",...i}=Z(e,t);switch(o){case"referenceHidden":{const r=await we(t,{...i,elementContext:"reference"}),l=ut(r,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:ct(l)}}}case"escaped":{const r=await we(t,{...i,altBoundary:!0}),l=ut(r,n.floating);return{data:{escapedOffsets:l,escaped:ct(l)}}}default:return{}}}}};async function On(e,t){const{placement:n,platform:o,elements:i}=e,r=await(o.isRTL==null?void 0:o.isRTL(i.floating)),l=ee(n),s=ge(n),u=re(n)==="y",d=["left","top"].includes(l)?-1:1,a=r&&u?-1:1,c=Z(t,e);let{mainAxis:v,crossAxis:f,alignmentAxis:p}=typeof c=="number"?{mainAxis:c,crossAxis:0,alignmentAxis:null}:{mainAxis:c.mainAxis||0,crossAxis:c.crossAxis||0,alignmentAxis:c.alignmentAxis};return s&&typeof p=="number"&&(f=s==="end"?p*-1:p),u?{x:f*a,y:v*d}:{x:v*d,y:f*a}}const An=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:i,y:r,placement:l,middlewareData:s}=t,u=await On(t,e);return l===((n=s.offset)==null?void 0:n.placement)&&(o=s.arrow)!=null&&o.alignmentOffset?{}:{x:i+u.x,y:r+u.y,data:{...u,placement:l}}}}},En=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:i}=t,{mainAxis:r=!0,crossAxis:l=!1,limiter:s={fn:m=>{let{x:h,y:b}=m;return{x:h,y:b}}},...u}=Z(e,t),d={x:n,y:o},a=await we(t,u),c=re(ee(i)),v=qe(c);let f=d[v],p=d[c];if(r){const m=v==="y"?"top":"left",h=v==="y"?"bottom":"right",b=f+a[m],y=f-a[h];f=ze(b,f,y)}if(l){const m=c==="y"?"top":"left",h=c==="y"?"bottom":"right",b=p+a[m],y=p-a[h];p=ze(b,p,y)}const g=s.fn({...t,[v]:f,[c]:p});return{...g,data:{x:g.x-n,y:g.y-o,enabled:{[v]:r,[c]:l}}}}}},Pn=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:o,placement:i,rects:r,middlewareData:l}=t,{offset:s=0,mainAxis:u=!0,crossAxis:d=!0}=Z(e,t),a={x:n,y:o},c=re(i),v=qe(c);let f=a[v],p=a[c];const g=Z(s,t),m=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(u){const y=v==="y"?"height":"width",C=r.reference[v]-r.floating[y]+m.mainAxis,x=r.reference[v]+r.reference[y]-m.mainAxis;fx&&(f=x)}if(d){var h,b;const y=v==="y"?"width":"height",C=["top","left"].includes(ee(i)),x=r.reference[c]-r.floating[y]+(C&&((h=l.offset)==null?void 0:h[c])||0)+(C?0:m.crossAxis),T=r.reference[c]+r.reference[y]+(C?0:((b=l.offset)==null?void 0:b[c])||0)-(C?m.crossAxis:0);pT&&(p=T)}return{[v]:f,[c]:p}}}},Tn=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,o;const{placement:i,rects:r,platform:l,elements:s}=t,{apply:u=()=>{},...d}=Z(e,t),a=await we(t,d),c=ee(i),v=ge(i),f=re(i)==="y",{width:p,height:g}=r.floating;let m,h;c==="top"||c==="bottom"?(m=c,h=v===(await(l.isRTL==null?void 0:l.isRTL(s.floating))?"start":"end")?"left":"right"):(h=c,m=v==="end"?"top":"bottom");const b=g-a.top-a.bottom,y=p-a.left-a.right,C=ie(g-a[m],b),x=ie(p-a[h],y),T=!t.middlewareData.shift;let A=C,R=x;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=y),(o=t.middlewareData.shift)!=null&&o.enabled.y&&(A=b),T&&!v){const E=H(a.left,0),z=H(a.right,0),k=H(a.top,0),F=H(a.bottom,0);f?R=p-2*(E!==0||z!==0?E+z:H(a.left,a.right)):A=g-2*(k!==0||F!==0?k+F:H(a.top,a.bottom))}await u({...t,availableWidth:R,availableHeight:A});const L=await l.getDimensions(s.floating);return p!==L.width||g!==L.height?{reset:{rects:!0}}:{}}}};function ke(){return typeof window<"u"}function ce(e){return Ze(e)?(e.nodeName||"").toLowerCase():"#document"}function W(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function q(e){var t;return(t=(Ze(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Ze(e){return ke()?e instanceof Node||e instanceof W(e).Node:!1}function V(e){return ke()?e instanceof Element||e instanceof W(e).Element:!1}function G(e){return ke()?e instanceof HTMLElement||e instanceof W(e).HTMLElement:!1}function dt(e){return!ke()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof W(e).ShadowRoot}function xe(e){const{overflow:t,overflowX:n,overflowY:o,display:i}=j(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!["inline","contents"].includes(i)}function Dn(e){return["table","td","th"].includes(ce(e))}function Me(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function et(e){const t=tt(),n=V(e)?j(e):e;return["transform","translate","scale","rotate","perspective"].some(o=>n[o]?n[o]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(o=>(n.willChange||"").includes(o))||["paint","layout","strict","content"].some(o=>(n.contain||"").includes(o))}function _n(e){let t=le(e);for(;G(t)&&!me(t);){if(et(t))return t;if(Me(t))return null;t=le(t)}return null}function tt(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function me(e){return["html","body","#document"].includes(ce(e))}function j(e){return W(e).getComputedStyle(e)}function Ne(e){return V(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function le(e){if(ce(e)==="html")return e;const t=e.assignedSlot||e.parentNode||dt(e)&&e.host||q(e);return dt(t)?t.host:t}function Dt(e){const t=le(e);return me(t)?e.ownerDocument?e.ownerDocument.body:e.body:G(t)&&xe(t)?t:Dt(t)}function be(e,t,n){var o;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Dt(e),r=i===((o=e.ownerDocument)==null?void 0:o.body),l=W(i);if(r){const s=je(l);return t.concat(l,l.visualViewport||[],xe(i)?i:[],s&&n?be(s):[])}return t.concat(i,be(i,[],n))}function je(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _t(e){const t=j(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const i=G(e),r=i?e.offsetWidth:n,l=i?e.offsetHeight:o,s=_e(n)!==r||_e(o)!==l;return s&&(n=r,o=l),{width:n,height:o,$:s}}function nt(e){return V(e)?e:e.contextElement}function ve(e){const t=nt(e);if(!G(t))return X(1);const n=t.getBoundingClientRect(),{width:o,height:i,$:r}=_t(t);let l=(r?_e(n.width):n.width)/o,s=(r?_e(n.height):n.height)/i;return(!l||!Number.isFinite(l))&&(l=1),(!s||!Number.isFinite(s))&&(s=1),{x:l,y:s}}const Rn=X(0);function Rt(e){const t=W(e);return!tt()||!t.visualViewport?Rn:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Sn(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==W(e)?!1:t}function ue(e,t,n,o){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),r=nt(e);let l=X(1);t&&(o?V(o)&&(l=ve(o)):l=ve(e));const s=Sn(r,n,o)?Rt(r):X(0);let u=(i.left+s.x)/l.x,d=(i.top+s.y)/l.y,a=i.width/l.x,c=i.height/l.y;if(r){const v=W(r),f=o&&V(o)?W(o):o;let p=v,g=je(p);for(;g&&o&&f!==p;){const m=ve(g),h=g.getBoundingClientRect(),b=j(g),y=h.left+(g.clientLeft+parseFloat(b.paddingLeft))*m.x,C=h.top+(g.clientTop+parseFloat(b.paddingTop))*m.y;u*=m.x,d*=m.y,a*=m.x,c*=m.y,u+=y,d+=C,p=W(g),g=je(p)}}return Se({width:a,height:c,x:u,y:d})}function ot(e,t){const n=Ne(e).scrollLeft;return t?t.left+n:ue(q(e)).left+n}function St(e,t,n){n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=o.left+t.scrollLeft-(n?0:ot(e,o)),r=o.top+t.scrollTop;return{x:i,y:r}}function $n(e){let{elements:t,rect:n,offsetParent:o,strategy:i}=e;const r=i==="fixed",l=q(o),s=t?Me(t.floating):!1;if(o===l||s&&r)return n;let u={scrollLeft:0,scrollTop:0},d=X(1);const a=X(0),c=G(o);if((c||!c&&!r)&&((ce(o)!=="body"||xe(l))&&(u=Ne(o)),G(o))){const f=ue(o);d=ve(o),a.x=f.x+o.clientLeft,a.y=f.y+o.clientTop}const v=l&&!c&&!r?St(l,u,!0):X(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-u.scrollLeft*d.x+a.x+v.x,y:n.y*d.y-u.scrollTop*d.y+a.y+v.y}}function Bn(e){return Array.from(e.getClientRects())}function Ln(e){const t=q(e),n=Ne(e),o=e.ownerDocument.body,i=H(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),r=H(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let l=-n.scrollLeft+ot(e);const s=-n.scrollTop;return j(o).direction==="rtl"&&(l+=H(t.clientWidth,o.clientWidth)-i),{width:i,height:r,x:l,y:s}}function kn(e,t){const n=W(e),o=q(e),i=n.visualViewport;let r=o.clientWidth,l=o.clientHeight,s=0,u=0;if(i){r=i.width,l=i.height;const d=tt();(!d||d&&t==="fixed")&&(s=i.offsetLeft,u=i.offsetTop)}return{width:r,height:l,x:s,y:u}}function Mn(e,t){const n=ue(e,!0,t==="fixed"),o=n.top+e.clientTop,i=n.left+e.clientLeft,r=G(e)?ve(e):X(1),l=e.clientWidth*r.x,s=e.clientHeight*r.y,u=i*r.x,d=o*r.y;return{width:l,height:s,x:u,y:d}}function ft(e,t,n){let o;if(t==="viewport")o=kn(e,n);else if(t==="document")o=Ln(q(e));else if(V(t))o=Mn(t,n);else{const i=Rt(e);o={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Se(o)}function $t(e,t){const n=le(e);return n===t||!V(n)||me(n)?!1:j(n).position==="fixed"||$t(n,t)}function Nn(e,t){const n=t.get(e);if(n)return n;let o=be(e,[],!1).filter(s=>V(s)&&ce(s)!=="body"),i=null;const r=j(e).position==="fixed";let l=r?le(e):e;for(;V(l)&&!me(l);){const s=j(l),u=et(l);!u&&s.position==="fixed"&&(i=null),(r?!u&&!i:!u&&s.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||xe(l)&&!u&&$t(e,l))?o=o.filter(a=>a!==l):i=s,l=le(l)}return t.set(e,o),o}function Fn(e){let{element:t,boundary:n,rootBoundary:o,strategy:i}=e;const l=[...n==="clippingAncestors"?Me(t)?[]:Nn(t,this._c):[].concat(n),o],s=l[0],u=l.reduce((d,a)=>{const c=ft(t,a,i);return d.top=H(c.top,d.top),d.right=ie(c.right,d.right),d.bottom=ie(c.bottom,d.bottom),d.left=H(c.left,d.left),d},ft(t,s,i));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function Hn(e){const{width:t,height:n}=_t(e);return{width:t,height:n}}function Wn(e,t,n){const o=G(t),i=q(t),r=n==="fixed",l=ue(e,!0,r,t);let s={scrollLeft:0,scrollTop:0};const u=X(0);if(o||!o&&!r)if((ce(t)!=="body"||xe(i))&&(s=Ne(t)),o){const v=ue(t,!0,r,t);u.x=v.x+t.clientLeft,u.y=v.y+t.clientTop}else i&&(u.x=ot(i));const d=i&&!o&&!r?St(i,s):X(0),a=l.left+s.scrollLeft-u.x-d.x,c=l.top+s.scrollTop-u.y-d.y;return{x:a,y:c,width:l.width,height:l.height}}function Ie(e){return j(e).position==="static"}function pt(e,t){if(!G(e)||j(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return q(e)===n&&(n=n.ownerDocument.body),n}function Bt(e,t){const n=W(e);if(Me(e))return n;if(!G(e)){let i=le(e);for(;i&&!me(i);){if(V(i)&&!Ie(i))return i;i=le(i)}return n}let o=pt(e,t);for(;o&&Dn(o)&&Ie(o);)o=pt(o,t);return o&&me(o)&&Ie(o)&&!et(o)?n:o||_n(e)||n}const In=async function(e){const t=this.getOffsetParent||Bt,n=this.getDimensions,o=await n(e.floating);return{reference:Wn(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function zn(e){return j(e).direction==="rtl"}const Vn={convertOffsetParentRelativeRectToViewportRelativeRect:$n,getDocumentElement:q,getClippingRect:Fn,getOffsetParent:Bt,getElementRects:In,getClientRects:Bn,getDimensions:Hn,getScale:ve,isElement:V,isRTL:zn};function Lt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function jn(e,t){let n=null,o;const i=q(e);function r(){var s;clearTimeout(o),(s=n)==null||s.disconnect(),n=null}function l(s,u){s===void 0&&(s=!1),u===void 0&&(u=1),r();const d=e.getBoundingClientRect(),{left:a,top:c,width:v,height:f}=d;if(s||t(),!v||!f)return;const p=Ae(c),g=Ae(i.clientWidth-(a+v)),m=Ae(i.clientHeight-(c+f)),h=Ae(a),y={rootMargin:-p+"px "+-g+"px "+-m+"px "+-h+"px",threshold:H(0,ie(1,u))||1};let C=!0;function x(T){const A=T[0].intersectionRatio;if(A!==u){if(!C)return l();A?l(!1,A):o=setTimeout(()=>{l(!1,1e-7)},1e3)}A===1&&!Lt(d,e.getBoundingClientRect())&&l(),C=!1}try{n=new IntersectionObserver(x,{...y,root:i.ownerDocument})}catch{n=new IntersectionObserver(x,y)}n.observe(e)}return l(!0),r}function Un(e,t,n,o){o===void 0&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:u=!1}=o,d=nt(e),a=i||r?[...d?be(d):[],...be(t)]:[];a.forEach(h=>{i&&h.addEventListener("scroll",n,{passive:!0}),r&&h.addEventListener("resize",n)});const c=d&&s?jn(d,n):null;let v=-1,f=null;l&&(f=new ResizeObserver(h=>{let[b]=h;b&&b.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(v),v=requestAnimationFrame(()=>{var y;(y=f)==null||y.observe(t)})),n()}),d&&!u&&f.observe(d),f.observe(t));let p,g=u?ue(e):null;u&&m();function m(){const h=ue(e);g&&!Lt(g,h)&&n(),g=h,p=requestAnimationFrame(m)}return n(),()=>{var h;a.forEach(b=>{i&&b.removeEventListener("scroll",n),r&&b.removeEventListener("resize",n)}),c==null||c(),(h=f)==null||h.disconnect(),f=null,u&&cancelAnimationFrame(p)}}const Yn=An,Kn=En,vt=xn,Xn=Tn,Gn=Cn,qn=bn,Jn=Pn,Qn=(e,t,n)=>{const o=new Map,i={platform:Vn,...n},r={...i.platform,_c:o};return wn(e,t,{...i,platform:r})};function Zn(e){return e!=null&&typeof e=="object"&&"$el"in e}function Ue(e){if(Zn(e)){const t=e.$el;return Ze(t)&&ce(t)==="#comment"?null:t}return e}function pe(e){return typeof e=="function"?e():w(e)}function eo(e){return{name:"arrow",options:e,fn(t){const n=Ue(pe(e.element));return n==null?{}:qn({element:n,padding:e.padding}).fn(t)}}}function kt(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function mt(e,t){const n=kt(e);return Math.round(t*n)/n}function to(e,t,n){n===void 0&&(n={});const o=n.whileElementsMounted,i=O(()=>{var A;return(A=pe(n.open))!=null?A:!0}),r=O(()=>pe(n.middleware)),l=O(()=>{var A;return(A=pe(n.placement))!=null?A:"bottom"}),s=O(()=>{var A;return(A=pe(n.strategy))!=null?A:"absolute"}),u=O(()=>{var A;return(A=pe(n.transform))!=null?A:!0}),d=O(()=>Ue(e.value)),a=O(()=>Ue(t.value)),c=P(0),v=P(0),f=P(s.value),p=P(l.value),g=ht({}),m=P(!1),h=O(()=>{const A={position:f.value,left:"0",top:"0"};if(!a.value)return A;const R=mt(a.value,c.value),L=mt(a.value,v.value);return u.value?{...A,transform:"translate("+R+"px, "+L+"px)",...kt(a.value)>=1.5&&{willChange:"transform"}}:{position:f.value,left:R+"px",top:L+"px"}});let b;function y(){if(d.value==null||a.value==null)return;const A=i.value;Qn(d.value,a.value,{middleware:r.value,placement:l.value,strategy:s.value}).then(R=>{c.value=R.x,v.value=R.y,f.value=R.strategy,p.value=R.placement,g.value=R.middlewareData,m.value=A!==!1})}function C(){typeof b=="function"&&(b(),b=void 0)}function x(){if(C(),o===void 0){y();return}if(d.value!=null&&a.value!=null){b=o(d.value,a.value,y);return}}function T(){i.value||(m.value=!1)}return K([r,l,s,i],y,{flush:"sync"}),K([d,a],x,{flush:"sync"}),K(i,T,{flush:"sync"}),gt()&&yt(C),{x:de(c),y:de(v),strategy:de(f),placement:de(p),middlewareData:de(g),isPositioned:de(m),floatingStyles:h,update:y}}function Ce(e,t){const n=typeof e=="string"&&!t?`${e}Context`:t,o=Symbol(n);return[i=>{const r=Yt(o,i);if(r||r===null)return r;throw new Error(`Injection \`${o.toString()}\` not found. Component must be used within ${Array.isArray(e)?`one of the following components: ${e.join(", ")}`:`\`${e}\``}`)},i=>(ln(o,i),i)]}function Mt(e,t,n){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),o.dispatchEvent(i)}function no(e,t){var n;const o=ht();return Q(()=>{o.value=e()},{...t,flush:(n=void 0)!=null?n:"sync"}),Ct(o)}function Fe(e){return gt()?(yt(e),!0):!1}function oo(){const e=new Set,t=n=>{e.delete(n)};return{on:n=>{e.add(n);const o=()=>t(n);return Fe(o),{off:o}},off:t,trigger:(...n)=>Promise.all(Array.from(e).map(o=>o(...n)))}}function io(e){let t=!1,n;const o=rn(!0);return(...i)=>(t||(n=o.run(()=>e(...i)),t=!0),n)}function ae(e){return typeof e=="function"?e():w(e)}const Oe=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const ro=e=>typeof e<"u",lo=Object.prototype.toString,so=e=>lo.call(e)==="[object Object]",ao=()=>{};function uo(e,t=1e4){return on((n,o)=>{let i=ae(e),r;const l=()=>setTimeout(()=>{i=ae(e),o()},ae(t));return Fe(()=>{clearTimeout(r)}),{get(){return n(),i},set(s){i=s,o(),clearTimeout(r),r=l()}}})}function Nt(e,t,n={}){const{immediate:o=!0}=n,i=P(!1);let r=null;function l(){r&&(clearTimeout(r),r=null)}function s(){i.value=!1,l()}function u(...d){l(),i.value=!0,r=setTimeout(()=>{i.value=!1,r=null,e(...d)},ae(t))}return o&&(i.value=!0,Oe&&u()),Fe(s),{isPending:Ct(i),start:u,stop:s}}function He(e){var t;const n=ae(e);return(t=n==null?void 0:n.$el)!=null?t:n}const it=Oe?window:void 0;function Ye(...e){let t,n,o,i;if(typeof e[0]=="string"||Array.isArray(e[0])?([n,o,i]=e,t=it):[t,n,o,i]=e,!t)return ao;Array.isArray(n)||(n=[n]),Array.isArray(o)||(o=[o]);const r=[],l=()=>{r.forEach(a=>a()),r.length=0},s=(a,c,v,f)=>(a.addEventListener(c,v,f),()=>a.removeEventListener(c,v,f)),u=K(()=>[He(t),ae(i)],([a,c])=>{if(l(),!a)return;const v=so(c)?{...c}:c;r.push(...n.flatMap(f=>o.map(p=>s(a,f,p,v))))},{immediate:!0,flush:"post"}),d=()=>{u(),l()};return Fe(d),d}function co(e){return typeof e=="function"?e:typeof e=="string"?t=>t.key===e:Array.isArray(e)?t=>e.includes(t.key):()=>!0}function fo(...e){let t,n,o={};e.length===3?(t=e[0],n=e[1],o=e[2]):e.length===2?typeof e[1]=="object"?(t=!0,n=e[0],o=e[1]):(t=e[0],n=e[1]):(t=!0,n=e[0]);const{target:i=it,eventName:r="keydown",passive:l=!1,dedupe:s=!1}=o,u=co(t);return Ye(i,r,d=>{d.repeat&&ae(s)||u(d)&&n(d)},l)}function po(){const e=P(!1),t=he();return t&&$e(()=>{e.value=!0},t),e}function vo(e){return JSON.parse(JSON.stringify(e))}function mo(e,t,n,o={}){var i,r,l;const{clone:s=!1,passive:u=!1,eventName:d,deep:a=!1,defaultValue:c,shouldEmit:v}=o,f=he(),p=n||(f==null?void 0:f.emit)||((i=f==null?void 0:f.$emit)==null?void 0:i.bind(f))||((l=(r=f==null?void 0:f.proxy)==null?void 0:r.$emit)==null?void 0:l.bind(f==null?void 0:f.proxy));let g=d;g=g||`update:${t.toString()}`;const m=y=>s?typeof s=="function"?s(y):vo(y):y,h=()=>ro(e[t])?m(e[t]):c,b=y=>{v?v(y)&&p(g,y):p(g,y)};if(u){const y=h(),C=P(y);let x=!1;return K(()=>e[t],T=>{x||(x=!0,C.value=m(T),Be(()=>x=!1))}),K(C,T=>{!x&&(T!==e[t]||a)&&b(T)},{deep:a}),C}else return O({get(){return h()},set(y){b(y)}})}function rt(e){return e?e.flatMap(t=>t.type===Pt?rt(t.children):[t]):[]}const[ho,mi]=Ce("ConfigProvider");function go(e){const t=he(),n=t==null?void 0:t.type.emits,o={};return n!=null&&n.length||console.warn(`No emitted event found. Please check component: ${t==null?void 0:t.type.__name}`),n==null||n.forEach(i=>{o[Qt(Et(i))]=(...r)=>e(i,...r)}),o}function Ft(e){const t=he(),n=Object.keys((t==null?void 0:t.type.props)??{}).reduce((i,r)=>{const l=(t==null?void 0:t.type.props[r]).default;return l!==void 0&&(i[r]=l),i},{}),o=Jt(e);return O(()=>{const i={},r=(t==null?void 0:t.vnode.props)??{};return Object.keys(r).forEach(l=>{i[Et(l)]=r[l]}),Object.keys({...n,...i}).reduce((l,s)=>(o.value[s]!==void 0&&(l[s]=o.value[s]),l),{})})}function yo(e,t){const n=Ft(e),o=t?go(t):{};return O(()=>({...n.value,...o}))}function I(){const e=he(),t=P(),n=O(()=>{var l,s;return["#text","#comment"].includes((l=t.value)==null?void 0:l.$el.nodeName)?(s=t.value)==null?void 0:s.$el.nextElementSibling:He(t)}),o=Object.assign({},e.exposed),i={};for(const l in e.props)Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>e.props[l]});if(Object.keys(o).length>0)for(const l in o)Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>o[l]});Object.defineProperty(i,"$el",{enumerable:!0,configurable:!0,get:()=>e.vnode.el}),e.exposed=i;function r(l){t.value=l,l&&(Object.defineProperty(i,"$el",{enumerable:!0,configurable:!0,get:()=>l instanceof Element?l:l.$el}),e.exposed=i)}return{forwardRef:r,currentRef:t,currentElement:n}}function wo(e,t){const n=uo(!1,300),o=P(null),i=oo();function r(){o.value=null,n.value=!1}function l(s,u){const d=s.currentTarget,a={x:s.clientX,y:s.clientY},c=bo(a,d.getBoundingClientRect()),v=xo(a,c),f=Co(u.getBoundingClientRect()),p=Ao([...v,...f]);o.value=p,n.value=!0}return Q(s=>{if(e.value&&t.value){const u=a=>l(a,t.value),d=a=>l(a,e.value);e.value.addEventListener("pointerleave",u),t.value.addEventListener("pointerleave",d),s(()=>{var a,c;(a=e.value)==null||a.removeEventListener("pointerleave",u),(c=t.value)==null||c.removeEventListener("pointerleave",d)})}}),Q(s=>{var u;if(o.value){const d=a=>{var c,v;if(!o.value)return;const f=a.target,p={x:a.clientX,y:a.clientY},g=((c=e.value)==null?void 0:c.contains(f))||((v=t.value)==null?void 0:v.contains(f)),m=!Oo(p,o.value),h=!!f.closest("[data-grace-area-trigger]");g?r():(m||h)&&(r(),i.trigger())};(u=e.value)==null||u.ownerDocument.addEventListener("pointermove",d),s(()=>{var a;return(a=e.value)==null?void 0:a.ownerDocument.removeEventListener("pointermove",d)})}}),{isPointerInTransit:n,onPointerExit:i.on}}function bo(e,t){const n=Math.abs(t.top-e.y),o=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),r=Math.abs(t.left-e.x);switch(Math.min(n,o,i,r)){case r:return"left";case i:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function xo(e,t,n=5){const o=[];switch(t){case"top":o.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":o.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":o.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":o.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return o}function Co(e){const{top:t,right:n,bottom:o,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:o},{x:i,y:o}]}function Oo(e,t){const{x:n,y:o}=e;let i=!1;for(let r=0,l=t.length-1;ro!=a>o&&n<(d-s)*(o-u)/(a-u)+s&&(i=!i)}return i}function Ao(e){const t=e.slice();return t.sort((n,o)=>n.xo.x?1:n.yo.y?1:0),Eo(t)}function Eo(e){if(e.length<=1)return e.slice();const t=[];for(let o=0;o=2;){const r=t[t.length-1],l=t[t.length-2];if((r.x-l.x)*(i.y-l.y)>=(r.y-l.y)*(i.x-l.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let o=e.length-1;o>=0;o--){const i=e[o];for(;n.length>=2;){const r=n[n.length-1],l=n[n.length-2];if((r.x-l.x)*(i.y-l.y)>=(r.y-l.y)*(i.x-l.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}let Po=0;function To(e,t="radix"){const n=ho({useId:void 0});return st?`${t}-${st()}`:n.useId?`${t}-${n.useId()}`:`${t}-${++Po}`}function Do(e){const t=P(),n=O(()=>{var i;return((i=t.value)==null?void 0:i.width)??0}),o=O(()=>{var i;return((i=t.value)==null?void 0:i.height)??0});return $e(()=>{const i=He(e);if(i){t.value={width:i.offsetWidth,height:i.offsetHeight};const r=new ResizeObserver(l=>{if(!Array.isArray(l)||!l.length)return;const s=l[0];let u,d;if("borderBoxSize"in s){const a=s.borderBoxSize,c=Array.isArray(a)?a[0]:a;u=c.inlineSize,d=c.blockSize}else u=i.offsetWidth,d=i.offsetHeight;t.value={width:u,height:d}});return r.observe(i,{box:"border-box"}),()=>r.unobserve(i)}else t.value=void 0}),{width:n,height:o}}function _o(e,t){const n=P(e);function o(i){return t[n.value][i]??n.value}return{state:n,dispatch:i=>{n.value=o(i)}}}const Ro=_({name:"PrimitiveSlot",inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{var o,i;if(!n.default)return null;const r=rt(n.default()),l=r.findIndex(a=>a.type!==At);if(l===-1)return r;const s=r[l];(o=s.props)==null||delete o.ref;const u=s.props?se(t,s.props):t;t.class&&(i=s.props)!=null&&i.class&&delete s.props.class;const d=qt(s,u);for(const a in u)a.startsWith("on")&&(d.props||(d.props={}),d.props[a]=u[a]);return r.length===1?d:(r[l]=d,r)}}}),ye=_({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(e,{attrs:t,slots:n}){const o=e.asChild?"template":e.as;return typeof o=="string"&&["area","img","input"].includes(o)?()=>Pe(o,t):o!=="template"?()=>Pe(e.as,t,{default:n.default}):()=>Pe(Ro,t,{default:n.default})}});function So(e,t){var n;const o=P({}),i=P("none"),r=P(e),l=e.value?"mounted":"unmounted";let s;const u=((n=t.value)==null?void 0:n.ownerDocument.defaultView)??it,{state:d,dispatch:a}=_o(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}}),c=m=>{var h;if(Oe){const b=new CustomEvent(m,{bubbles:!1,cancelable:!1});(h=t.value)==null||h.dispatchEvent(b)}};K(e,async(m,h)=>{var b;const y=h!==m;if(await Be(),y){const C=i.value,x=Ee(t.value);m?(a("MOUNT"),c("enter"),x==="none"&&c("after-enter")):x==="none"||((b=o.value)==null?void 0:b.display)==="none"?(a("UNMOUNT"),c("leave"),c("after-leave")):h&&C!==x?(a("ANIMATION_OUT"),c("leave")):(a("UNMOUNT"),c("after-leave"))}},{immediate:!0});const v=m=>{const h=Ee(t.value),b=h.includes(m.animationName),y=d.value==="mounted"?"enter":"leave";if(m.target===t.value&&b&&(c(`after-${y}`),a("ANIMATION_END"),!r.value)){const C=t.value.style.animationFillMode;t.value.style.animationFillMode="forwards",s=u==null?void 0:u.setTimeout(()=>{var x;((x=t.value)==null?void 0:x.style.animationFillMode)==="forwards"&&(t.value.style.animationFillMode=C)})}m.target===t.value&&h==="none"&&a("ANIMATION_END")},f=m=>{m.target===t.value&&(i.value=Ee(t.value))},p=K(t,(m,h)=>{m?(o.value=getComputedStyle(m),m.addEventListener("animationstart",f),m.addEventListener("animationcancel",v),m.addEventListener("animationend",v)):(a("ANIMATION_END"),s!==void 0&&(u==null||u.clearTimeout(s)),h==null||h.removeEventListener("animationstart",f),h==null||h.removeEventListener("animationcancel",v),h==null||h.removeEventListener("animationend",v))},{immediate:!0}),g=K(d,()=>{const m=Ee(t.value);i.value=d.value==="mounted"?m:"none"});return nn(()=>{p(),g()}),{isPresent:O(()=>["mounted","unmountSuspended"].includes(d.value))}}function Ee(e){return e&&getComputedStyle(e).animationName||"none"}const $o=_({name:"Presence",props:{present:{type:Boolean,required:!0},forceMount:{type:Boolean}},slots:{},setup(e,{slots:t,expose:n}){var o;const{present:i,forceMount:r}=xt(e),l=P(),{isPresent:s}=So(i,l);n({present:s});let u=t.default({present:s});u=rt(u||[]);const d=he();if(u&&(u==null?void 0:u.length)>1){const a=(o=d==null?void 0:d.parent)!=null&&o.type.name?`<${d.parent.type.name} />`:"component";throw new Error([`Detected an invalid children for \`${a}\` for \`Presence\` component.`,"","Note: Presence works similarly to `v-if` directly, but it waits for animation/transition to finished before unmounting. So it expect only one direct child of valid VNode type.","You can apply a few solutions:",["Provide a single child element so that `presence` directive attach correctly.","Ensure the first child is an actual element instead of a raw text node or comment node."].map(c=>` - ${c}`).join(` +import"./live2d-zip-loader-C5j9stxV.js";import{h as O,g as P,G as ht,w as K,ah as gt,ai as yt,bP as de,e as w,d as _,x as M,o as $,y as D,p as B,m as $e,b as Y,bQ as se,bR as jt,bS as wt,bT as bt,bU as Ut,E as xt,bV as he,bW as Yt,bv as Be,bX as Ct,bY as st,bZ as Pe,af as Q,C as Ot,b_ as Kt,ab as Xt,b$ as At,bH as Xe,D as Ge,c0 as Gt,c as De,n as Le,c1 as qt,br as Jt,c2 as Et,c3 as Qt,c4 as Zt,c5 as en,c6 as tn,H as nn,bx as Pt,a as fe,c7 as on,c8 as rn,c9 as ln,v as sn,by as an,z as Te,ca as un}from"./index-Dlp4W1Zl.js";import{_ as cn}from"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";const dn=["top","right","bottom","left"],ie=Math.min,H=Math.max,_e=Math.round,Ae=Math.floor,X=e=>({x:e,y:e}),fn={left:"right",right:"left",bottom:"top",top:"bottom"},pn={start:"end",end:"start"};function ze(e,t,n){return H(e,ie(t,n))}function Z(e,t){return typeof e=="function"?e(t):e}function ee(e){return e.split("-")[0]}function ge(e){return e.split("-")[1]}function qe(e){return e==="x"?"y":"x"}function Je(e){return e==="y"?"height":"width"}function re(e){return["top","bottom"].includes(ee(e))?"y":"x"}function Qe(e){return qe(re(e))}function vn(e,t,n){n===void 0&&(n=!1);const o=ge(e),i=Qe(e),r=Je(i);let l=i==="x"?o===(n?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[r]>t.floating[r]&&(l=Re(l)),[l,Re(l)]}function mn(e){const t=Re(e);return[Ve(e),t,Ve(t)]}function Ve(e){return e.replace(/start|end/g,t=>pn[t])}function hn(e,t,n){const o=["left","right"],i=["right","left"],r=["top","bottom"],l=["bottom","top"];switch(e){case"top":case"bottom":return n?t?i:o:t?o:i;case"left":case"right":return t?r:l;default:return[]}}function gn(e,t,n,o){const i=ge(e);let r=hn(ee(e),n==="start",o);return i&&(r=r.map(l=>l+"-"+i),t&&(r=r.concat(r.map(Ve)))),r}function Re(e){return e.replace(/left|right|bottom|top/g,t=>fn[t])}function yn(e){return{top:0,right:0,bottom:0,left:0,...e}}function Tt(e){return typeof e!="number"?yn(e):{top:e,right:e,bottom:e,left:e}}function Se(e){const{x:t,y:n,width:o,height:i}=e;return{width:o,height:i,top:n,left:t,right:t+o,bottom:n+i,x:t,y:n}}function at(e,t,n){let{reference:o,floating:i}=e;const r=re(t),l=Qe(t),s=Je(l),u=ee(t),d=r==="y",a=o.x+o.width/2-i.width/2,c=o.y+o.height/2-i.height/2,v=o[s]/2-i[s]/2;let f;switch(u){case"top":f={x:a,y:o.y-i.height};break;case"bottom":f={x:a,y:o.y+o.height};break;case"right":f={x:o.x+o.width,y:c};break;case"left":f={x:o.x-i.width,y:c};break;default:f={x:o.x,y:o.y}}switch(ge(t)){case"start":f[l]-=v*(n&&d?-1:1);break;case"end":f[l]+=v*(n&&d?-1:1);break}return f}const wn=async(e,t,n)=>{const{placement:o="bottom",strategy:i="absolute",middleware:r=[],platform:l}=n,s=r.filter(Boolean),u=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:e,floating:t,strategy:i}),{x:a,y:c}=at(d,o,u),v=o,f={},p=0;for(let g=0;g({name:"arrow",options:e,async fn(t){const{x:n,y:o,placement:i,rects:r,platform:l,elements:s,middlewareData:u}=t,{element:d,padding:a=0}=Z(e,t)||{};if(d==null)return{};const c=Tt(a),v={x:n,y:o},f=Qe(i),p=Je(f),g=await l.getDimensions(d),m=f==="y",h=m?"top":"left",b=m?"bottom":"right",y=m?"clientHeight":"clientWidth",C=r.reference[p]+r.reference[f]-v[f]-r.floating[p],x=v[f]-r.reference[f],T=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let A=T?T[y]:0;(!A||!await(l.isElement==null?void 0:l.isElement(T)))&&(A=s.floating[y]||r.floating[p]);const R=C/2-x/2,L=A/2-g[p]/2-1,E=ie(c[h],L),z=ie(c[b],L),k=E,F=A-g[p]-z,S=A/2-g[p]/2+R,te=ze(k,S,F),N=!u.arrow&&ge(i)!=null&&S!==te&&r.reference[p]/2-(SS<=0)){var z,k;const S=(((z=r.flip)==null?void 0:z.index)||0)+1,te=A[S];if(te)return{data:{index:S,overflows:E},reset:{placement:te}};let N=(k=E.filter(U=>U.overflows[0]<=0).sort((U,ne)=>U.overflows[1]-ne.overflows[1])[0])==null?void 0:k.placement;if(!N)switch(f){case"bestFit":{var F;const U=(F=E.filter(ne=>{if(T){const oe=re(ne.placement);return oe===b||oe==="y"}return!0}).map(ne=>[ne.placement,ne.overflows.filter(oe=>oe>0).reduce((oe,Vt)=>oe+Vt,0)]).sort((ne,oe)=>ne[1]-oe[1])[0])==null?void 0:F[0];U&&(N=U);break}case"initialPlacement":N=s;break}if(i!==N)return{reset:{placement:N}}}return{}}}};function ut(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function ct(e){return dn.some(t=>e[t]>=0)}const Cn=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:o="referenceHidden",...i}=Z(e,t);switch(o){case"referenceHidden":{const r=await we(t,{...i,elementContext:"reference"}),l=ut(r,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:ct(l)}}}case"escaped":{const r=await we(t,{...i,altBoundary:!0}),l=ut(r,n.floating);return{data:{escapedOffsets:l,escaped:ct(l)}}}default:return{}}}}};async function On(e,t){const{placement:n,platform:o,elements:i}=e,r=await(o.isRTL==null?void 0:o.isRTL(i.floating)),l=ee(n),s=ge(n),u=re(n)==="y",d=["left","top"].includes(l)?-1:1,a=r&&u?-1:1,c=Z(t,e);let{mainAxis:v,crossAxis:f,alignmentAxis:p}=typeof c=="number"?{mainAxis:c,crossAxis:0,alignmentAxis:null}:{mainAxis:c.mainAxis||0,crossAxis:c.crossAxis||0,alignmentAxis:c.alignmentAxis};return s&&typeof p=="number"&&(f=s==="end"?p*-1:p),u?{x:f*a,y:v*d}:{x:v*d,y:f*a}}const An=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,o;const{x:i,y:r,placement:l,middlewareData:s}=t,u=await On(t,e);return l===((n=s.offset)==null?void 0:n.placement)&&(o=s.arrow)!=null&&o.alignmentOffset?{}:{x:i+u.x,y:r+u.y,data:{...u,placement:l}}}}},En=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:o,placement:i}=t,{mainAxis:r=!0,crossAxis:l=!1,limiter:s={fn:m=>{let{x:h,y:b}=m;return{x:h,y:b}}},...u}=Z(e,t),d={x:n,y:o},a=await we(t,u),c=re(ee(i)),v=qe(c);let f=d[v],p=d[c];if(r){const m=v==="y"?"top":"left",h=v==="y"?"bottom":"right",b=f+a[m],y=f-a[h];f=ze(b,f,y)}if(l){const m=c==="y"?"top":"left",h=c==="y"?"bottom":"right",b=p+a[m],y=p-a[h];p=ze(b,p,y)}const g=s.fn({...t,[v]:f,[c]:p});return{...g,data:{x:g.x-n,y:g.y-o,enabled:{[v]:r,[c]:l}}}}}},Pn=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:o,placement:i,rects:r,middlewareData:l}=t,{offset:s=0,mainAxis:u=!0,crossAxis:d=!0}=Z(e,t),a={x:n,y:o},c=re(i),v=qe(c);let f=a[v],p=a[c];const g=Z(s,t),m=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(u){const y=v==="y"?"height":"width",C=r.reference[v]-r.floating[y]+m.mainAxis,x=r.reference[v]+r.reference[y]-m.mainAxis;fx&&(f=x)}if(d){var h,b;const y=v==="y"?"width":"height",C=["top","left"].includes(ee(i)),x=r.reference[c]-r.floating[y]+(C&&((h=l.offset)==null?void 0:h[c])||0)+(C?0:m.crossAxis),T=r.reference[c]+r.reference[y]+(C?0:((b=l.offset)==null?void 0:b[c])||0)-(C?m.crossAxis:0);pT&&(p=T)}return{[v]:f,[c]:p}}}},Tn=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,o;const{placement:i,rects:r,platform:l,elements:s}=t,{apply:u=()=>{},...d}=Z(e,t),a=await we(t,d),c=ee(i),v=ge(i),f=re(i)==="y",{width:p,height:g}=r.floating;let m,h;c==="top"||c==="bottom"?(m=c,h=v===(await(l.isRTL==null?void 0:l.isRTL(s.floating))?"start":"end")?"left":"right"):(h=c,m=v==="end"?"top":"bottom");const b=g-a.top-a.bottom,y=p-a.left-a.right,C=ie(g-a[m],b),x=ie(p-a[h],y),T=!t.middlewareData.shift;let A=C,R=x;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(R=y),(o=t.middlewareData.shift)!=null&&o.enabled.y&&(A=b),T&&!v){const E=H(a.left,0),z=H(a.right,0),k=H(a.top,0),F=H(a.bottom,0);f?R=p-2*(E!==0||z!==0?E+z:H(a.left,a.right)):A=g-2*(k!==0||F!==0?k+F:H(a.top,a.bottom))}await u({...t,availableWidth:R,availableHeight:A});const L=await l.getDimensions(s.floating);return p!==L.width||g!==L.height?{reset:{rects:!0}}:{}}}};function ke(){return typeof window<"u"}function ce(e){return Ze(e)?(e.nodeName||"").toLowerCase():"#document"}function W(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function q(e){var t;return(t=(Ze(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Ze(e){return ke()?e instanceof Node||e instanceof W(e).Node:!1}function V(e){return ke()?e instanceof Element||e instanceof W(e).Element:!1}function G(e){return ke()?e instanceof HTMLElement||e instanceof W(e).HTMLElement:!1}function dt(e){return!ke()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof W(e).ShadowRoot}function xe(e){const{overflow:t,overflowX:n,overflowY:o,display:i}=j(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+n)&&!["inline","contents"].includes(i)}function Dn(e){return["table","td","th"].includes(ce(e))}function Me(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function et(e){const t=tt(),n=V(e)?j(e):e;return["transform","translate","scale","rotate","perspective"].some(o=>n[o]?n[o]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(o=>(n.willChange||"").includes(o))||["paint","layout","strict","content"].some(o=>(n.contain||"").includes(o))}function _n(e){let t=le(e);for(;G(t)&&!me(t);){if(et(t))return t;if(Me(t))return null;t=le(t)}return null}function tt(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function me(e){return["html","body","#document"].includes(ce(e))}function j(e){return W(e).getComputedStyle(e)}function Ne(e){return V(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function le(e){if(ce(e)==="html")return e;const t=e.assignedSlot||e.parentNode||dt(e)&&e.host||q(e);return dt(t)?t.host:t}function Dt(e){const t=le(e);return me(t)?e.ownerDocument?e.ownerDocument.body:e.body:G(t)&&xe(t)?t:Dt(t)}function be(e,t,n){var o;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=Dt(e),r=i===((o=e.ownerDocument)==null?void 0:o.body),l=W(i);if(r){const s=je(l);return t.concat(l,l.visualViewport||[],xe(i)?i:[],s&&n?be(s):[])}return t.concat(i,be(i,[],n))}function je(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function _t(e){const t=j(e);let n=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const i=G(e),r=i?e.offsetWidth:n,l=i?e.offsetHeight:o,s=_e(n)!==r||_e(o)!==l;return s&&(n=r,o=l),{width:n,height:o,$:s}}function nt(e){return V(e)?e:e.contextElement}function ve(e){const t=nt(e);if(!G(t))return X(1);const n=t.getBoundingClientRect(),{width:o,height:i,$:r}=_t(t);let l=(r?_e(n.width):n.width)/o,s=(r?_e(n.height):n.height)/i;return(!l||!Number.isFinite(l))&&(l=1),(!s||!Number.isFinite(s))&&(s=1),{x:l,y:s}}const Rn=X(0);function Rt(e){const t=W(e);return!tt()||!t.visualViewport?Rn:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Sn(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==W(e)?!1:t}function ue(e,t,n,o){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),r=nt(e);let l=X(1);t&&(o?V(o)&&(l=ve(o)):l=ve(e));const s=Sn(r,n,o)?Rt(r):X(0);let u=(i.left+s.x)/l.x,d=(i.top+s.y)/l.y,a=i.width/l.x,c=i.height/l.y;if(r){const v=W(r),f=o&&V(o)?W(o):o;let p=v,g=je(p);for(;g&&o&&f!==p;){const m=ve(g),h=g.getBoundingClientRect(),b=j(g),y=h.left+(g.clientLeft+parseFloat(b.paddingLeft))*m.x,C=h.top+(g.clientTop+parseFloat(b.paddingTop))*m.y;u*=m.x,d*=m.y,a*=m.x,c*=m.y,u+=y,d+=C,p=W(g),g=je(p)}}return Se({width:a,height:c,x:u,y:d})}function ot(e,t){const n=Ne(e).scrollLeft;return t?t.left+n:ue(q(e)).left+n}function St(e,t,n){n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=o.left+t.scrollLeft-(n?0:ot(e,o)),r=o.top+t.scrollTop;return{x:i,y:r}}function $n(e){let{elements:t,rect:n,offsetParent:o,strategy:i}=e;const r=i==="fixed",l=q(o),s=t?Me(t.floating):!1;if(o===l||s&&r)return n;let u={scrollLeft:0,scrollTop:0},d=X(1);const a=X(0),c=G(o);if((c||!c&&!r)&&((ce(o)!=="body"||xe(l))&&(u=Ne(o)),G(o))){const f=ue(o);d=ve(o),a.x=f.x+o.clientLeft,a.y=f.y+o.clientTop}const v=l&&!c&&!r?St(l,u,!0):X(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-u.scrollLeft*d.x+a.x+v.x,y:n.y*d.y-u.scrollTop*d.y+a.y+v.y}}function Bn(e){return Array.from(e.getClientRects())}function Ln(e){const t=q(e),n=Ne(e),o=e.ownerDocument.body,i=H(t.scrollWidth,t.clientWidth,o.scrollWidth,o.clientWidth),r=H(t.scrollHeight,t.clientHeight,o.scrollHeight,o.clientHeight);let l=-n.scrollLeft+ot(e);const s=-n.scrollTop;return j(o).direction==="rtl"&&(l+=H(t.clientWidth,o.clientWidth)-i),{width:i,height:r,x:l,y:s}}function kn(e,t){const n=W(e),o=q(e),i=n.visualViewport;let r=o.clientWidth,l=o.clientHeight,s=0,u=0;if(i){r=i.width,l=i.height;const d=tt();(!d||d&&t==="fixed")&&(s=i.offsetLeft,u=i.offsetTop)}return{width:r,height:l,x:s,y:u}}function Mn(e,t){const n=ue(e,!0,t==="fixed"),o=n.top+e.clientTop,i=n.left+e.clientLeft,r=G(e)?ve(e):X(1),l=e.clientWidth*r.x,s=e.clientHeight*r.y,u=i*r.x,d=o*r.y;return{width:l,height:s,x:u,y:d}}function ft(e,t,n){let o;if(t==="viewport")o=kn(e,n);else if(t==="document")o=Ln(q(e));else if(V(t))o=Mn(t,n);else{const i=Rt(e);o={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Se(o)}function $t(e,t){const n=le(e);return n===t||!V(n)||me(n)?!1:j(n).position==="fixed"||$t(n,t)}function Nn(e,t){const n=t.get(e);if(n)return n;let o=be(e,[],!1).filter(s=>V(s)&&ce(s)!=="body"),i=null;const r=j(e).position==="fixed";let l=r?le(e):e;for(;V(l)&&!me(l);){const s=j(l),u=et(l);!u&&s.position==="fixed"&&(i=null),(r?!u&&!i:!u&&s.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||xe(l)&&!u&&$t(e,l))?o=o.filter(a=>a!==l):i=s,l=le(l)}return t.set(e,o),o}function Fn(e){let{element:t,boundary:n,rootBoundary:o,strategy:i}=e;const l=[...n==="clippingAncestors"?Me(t)?[]:Nn(t,this._c):[].concat(n),o],s=l[0],u=l.reduce((d,a)=>{const c=ft(t,a,i);return d.top=H(c.top,d.top),d.right=ie(c.right,d.right),d.bottom=ie(c.bottom,d.bottom),d.left=H(c.left,d.left),d},ft(t,s,i));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function Hn(e){const{width:t,height:n}=_t(e);return{width:t,height:n}}function Wn(e,t,n){const o=G(t),i=q(t),r=n==="fixed",l=ue(e,!0,r,t);let s={scrollLeft:0,scrollTop:0};const u=X(0);if(o||!o&&!r)if((ce(t)!=="body"||xe(i))&&(s=Ne(t)),o){const v=ue(t,!0,r,t);u.x=v.x+t.clientLeft,u.y=v.y+t.clientTop}else i&&(u.x=ot(i));const d=i&&!o&&!r?St(i,s):X(0),a=l.left+s.scrollLeft-u.x-d.x,c=l.top+s.scrollTop-u.y-d.y;return{x:a,y:c,width:l.width,height:l.height}}function Ie(e){return j(e).position==="static"}function pt(e,t){if(!G(e)||j(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return q(e)===n&&(n=n.ownerDocument.body),n}function Bt(e,t){const n=W(e);if(Me(e))return n;if(!G(e)){let i=le(e);for(;i&&!me(i);){if(V(i)&&!Ie(i))return i;i=le(i)}return n}let o=pt(e,t);for(;o&&Dn(o)&&Ie(o);)o=pt(o,t);return o&&me(o)&&Ie(o)&&!et(o)?n:o||_n(e)||n}const In=async function(e){const t=this.getOffsetParent||Bt,n=this.getDimensions,o=await n(e.floating);return{reference:Wn(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function zn(e){return j(e).direction==="rtl"}const Vn={convertOffsetParentRelativeRectToViewportRelativeRect:$n,getDocumentElement:q,getClippingRect:Fn,getOffsetParent:Bt,getElementRects:In,getClientRects:Bn,getDimensions:Hn,getScale:ve,isElement:V,isRTL:zn};function Lt(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function jn(e,t){let n=null,o;const i=q(e);function r(){var s;clearTimeout(o),(s=n)==null||s.disconnect(),n=null}function l(s,u){s===void 0&&(s=!1),u===void 0&&(u=1),r();const d=e.getBoundingClientRect(),{left:a,top:c,width:v,height:f}=d;if(s||t(),!v||!f)return;const p=Ae(c),g=Ae(i.clientWidth-(a+v)),m=Ae(i.clientHeight-(c+f)),h=Ae(a),y={rootMargin:-p+"px "+-g+"px "+-m+"px "+-h+"px",threshold:H(0,ie(1,u))||1};let C=!0;function x(T){const A=T[0].intersectionRatio;if(A!==u){if(!C)return l();A?l(!1,A):o=setTimeout(()=>{l(!1,1e-7)},1e3)}A===1&&!Lt(d,e.getBoundingClientRect())&&l(),C=!1}try{n=new IntersectionObserver(x,{...y,root:i.ownerDocument})}catch{n=new IntersectionObserver(x,y)}n.observe(e)}return l(!0),r}function Un(e,t,n,o){o===void 0&&(o={});const{ancestorScroll:i=!0,ancestorResize:r=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:u=!1}=o,d=nt(e),a=i||r?[...d?be(d):[],...be(t)]:[];a.forEach(h=>{i&&h.addEventListener("scroll",n,{passive:!0}),r&&h.addEventListener("resize",n)});const c=d&&s?jn(d,n):null;let v=-1,f=null;l&&(f=new ResizeObserver(h=>{let[b]=h;b&&b.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(v),v=requestAnimationFrame(()=>{var y;(y=f)==null||y.observe(t)})),n()}),d&&!u&&f.observe(d),f.observe(t));let p,g=u?ue(e):null;u&&m();function m(){const h=ue(e);g&&!Lt(g,h)&&n(),g=h,p=requestAnimationFrame(m)}return n(),()=>{var h;a.forEach(b=>{i&&b.removeEventListener("scroll",n),r&&b.removeEventListener("resize",n)}),c==null||c(),(h=f)==null||h.disconnect(),f=null,u&&cancelAnimationFrame(p)}}const Yn=An,Kn=En,vt=xn,Xn=Tn,Gn=Cn,qn=bn,Jn=Pn,Qn=(e,t,n)=>{const o=new Map,i={platform:Vn,...n},r={...i.platform,_c:o};return wn(e,t,{...i,platform:r})};function Zn(e){return e!=null&&typeof e=="object"&&"$el"in e}function Ue(e){if(Zn(e)){const t=e.$el;return Ze(t)&&ce(t)==="#comment"?null:t}return e}function pe(e){return typeof e=="function"?e():w(e)}function eo(e){return{name:"arrow",options:e,fn(t){const n=Ue(pe(e.element));return n==null?{}:qn({element:n,padding:e.padding}).fn(t)}}}function kt(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function mt(e,t){const n=kt(e);return Math.round(t*n)/n}function to(e,t,n){n===void 0&&(n={});const o=n.whileElementsMounted,i=O(()=>{var A;return(A=pe(n.open))!=null?A:!0}),r=O(()=>pe(n.middleware)),l=O(()=>{var A;return(A=pe(n.placement))!=null?A:"bottom"}),s=O(()=>{var A;return(A=pe(n.strategy))!=null?A:"absolute"}),u=O(()=>{var A;return(A=pe(n.transform))!=null?A:!0}),d=O(()=>Ue(e.value)),a=O(()=>Ue(t.value)),c=P(0),v=P(0),f=P(s.value),p=P(l.value),g=ht({}),m=P(!1),h=O(()=>{const A={position:f.value,left:"0",top:"0"};if(!a.value)return A;const R=mt(a.value,c.value),L=mt(a.value,v.value);return u.value?{...A,transform:"translate("+R+"px, "+L+"px)",...kt(a.value)>=1.5&&{willChange:"transform"}}:{position:f.value,left:R+"px",top:L+"px"}});let b;function y(){if(d.value==null||a.value==null)return;const A=i.value;Qn(d.value,a.value,{middleware:r.value,placement:l.value,strategy:s.value}).then(R=>{c.value=R.x,v.value=R.y,f.value=R.strategy,p.value=R.placement,g.value=R.middlewareData,m.value=A!==!1})}function C(){typeof b=="function"&&(b(),b=void 0)}function x(){if(C(),o===void 0){y();return}if(d.value!=null&&a.value!=null){b=o(d.value,a.value,y);return}}function T(){i.value||(m.value=!1)}return K([r,l,s,i],y,{flush:"sync"}),K([d,a],x,{flush:"sync"}),K(i,T,{flush:"sync"}),gt()&&yt(C),{x:de(c),y:de(v),strategy:de(f),placement:de(p),middlewareData:de(g),isPositioned:de(m),floatingStyles:h,update:y}}function Ce(e,t){const n=typeof e=="string"&&!t?`${e}Context`:t,o=Symbol(n);return[i=>{const r=Yt(o,i);if(r||r===null)return r;throw new Error(`Injection \`${o.toString()}\` not found. Component must be used within ${Array.isArray(e)?`one of the following components: ${e.join(", ")}`:`\`${e}\``}`)},i=>(ln(o,i),i)]}function Mt(e,t,n){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),o.dispatchEvent(i)}function no(e,t){var n;const o=ht();return Q(()=>{o.value=e()},{...t,flush:(n=void 0)!=null?n:"sync"}),Ct(o)}function Fe(e){return gt()?(yt(e),!0):!1}function oo(){const e=new Set,t=n=>{e.delete(n)};return{on:n=>{e.add(n);const o=()=>t(n);return Fe(o),{off:o}},off:t,trigger:(...n)=>Promise.all(Array.from(e).map(o=>o(...n)))}}function io(e){let t=!1,n;const o=rn(!0);return(...i)=>(t||(n=o.run(()=>e(...i)),t=!0),n)}function ae(e){return typeof e=="function"?e():w(e)}const Oe=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const ro=e=>typeof e<"u",lo=Object.prototype.toString,so=e=>lo.call(e)==="[object Object]",ao=()=>{};function uo(e,t=1e4){return on((n,o)=>{let i=ae(e),r;const l=()=>setTimeout(()=>{i=ae(e),o()},ae(t));return Fe(()=>{clearTimeout(r)}),{get(){return n(),i},set(s){i=s,o(),clearTimeout(r),r=l()}}})}function Nt(e,t,n={}){const{immediate:o=!0}=n,i=P(!1);let r=null;function l(){r&&(clearTimeout(r),r=null)}function s(){i.value=!1,l()}function u(...d){l(),i.value=!0,r=setTimeout(()=>{i.value=!1,r=null,e(...d)},ae(t))}return o&&(i.value=!0,Oe&&u()),Fe(s),{isPending:Ct(i),start:u,stop:s}}function He(e){var t;const n=ae(e);return(t=n==null?void 0:n.$el)!=null?t:n}const it=Oe?window:void 0;function Ye(...e){let t,n,o,i;if(typeof e[0]=="string"||Array.isArray(e[0])?([n,o,i]=e,t=it):[t,n,o,i]=e,!t)return ao;Array.isArray(n)||(n=[n]),Array.isArray(o)||(o=[o]);const r=[],l=()=>{r.forEach(a=>a()),r.length=0},s=(a,c,v,f)=>(a.addEventListener(c,v,f),()=>a.removeEventListener(c,v,f)),u=K(()=>[He(t),ae(i)],([a,c])=>{if(l(),!a)return;const v=so(c)?{...c}:c;r.push(...n.flatMap(f=>o.map(p=>s(a,f,p,v))))},{immediate:!0,flush:"post"}),d=()=>{u(),l()};return Fe(d),d}function co(e){return typeof e=="function"?e:typeof e=="string"?t=>t.key===e:Array.isArray(e)?t=>e.includes(t.key):()=>!0}function fo(...e){let t,n,o={};e.length===3?(t=e[0],n=e[1],o=e[2]):e.length===2?typeof e[1]=="object"?(t=!0,n=e[0],o=e[1]):(t=e[0],n=e[1]):(t=!0,n=e[0]);const{target:i=it,eventName:r="keydown",passive:l=!1,dedupe:s=!1}=o,u=co(t);return Ye(i,r,d=>{d.repeat&&ae(s)||u(d)&&n(d)},l)}function po(){const e=P(!1),t=he();return t&&$e(()=>{e.value=!0},t),e}function vo(e){return JSON.parse(JSON.stringify(e))}function mo(e,t,n,o={}){var i,r,l;const{clone:s=!1,passive:u=!1,eventName:d,deep:a=!1,defaultValue:c,shouldEmit:v}=o,f=he(),p=n||(f==null?void 0:f.emit)||((i=f==null?void 0:f.$emit)==null?void 0:i.bind(f))||((l=(r=f==null?void 0:f.proxy)==null?void 0:r.$emit)==null?void 0:l.bind(f==null?void 0:f.proxy));let g=d;g=g||`update:${t.toString()}`;const m=y=>s?typeof s=="function"?s(y):vo(y):y,h=()=>ro(e[t])?m(e[t]):c,b=y=>{v?v(y)&&p(g,y):p(g,y)};if(u){const y=h(),C=P(y);let x=!1;return K(()=>e[t],T=>{x||(x=!0,C.value=m(T),Be(()=>x=!1))}),K(C,T=>{!x&&(T!==e[t]||a)&&b(T)},{deep:a}),C}else return O({get(){return h()},set(y){b(y)}})}function rt(e){return e?e.flatMap(t=>t.type===Pt?rt(t.children):[t]):[]}const[ho,mi]=Ce("ConfigProvider");function go(e){const t=he(),n=t==null?void 0:t.type.emits,o={};return n!=null&&n.length||console.warn(`No emitted event found. Please check component: ${t==null?void 0:t.type.__name}`),n==null||n.forEach(i=>{o[Qt(Et(i))]=(...r)=>e(i,...r)}),o}function Ft(e){const t=he(),n=Object.keys((t==null?void 0:t.type.props)??{}).reduce((i,r)=>{const l=(t==null?void 0:t.type.props[r]).default;return l!==void 0&&(i[r]=l),i},{}),o=Jt(e);return O(()=>{const i={},r=(t==null?void 0:t.vnode.props)??{};return Object.keys(r).forEach(l=>{i[Et(l)]=r[l]}),Object.keys({...n,...i}).reduce((l,s)=>(o.value[s]!==void 0&&(l[s]=o.value[s]),l),{})})}function yo(e,t){const n=Ft(e),o=t?go(t):{};return O(()=>({...n.value,...o}))}function I(){const e=he(),t=P(),n=O(()=>{var l,s;return["#text","#comment"].includes((l=t.value)==null?void 0:l.$el.nodeName)?(s=t.value)==null?void 0:s.$el.nextElementSibling:He(t)}),o=Object.assign({},e.exposed),i={};for(const l in e.props)Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>e.props[l]});if(Object.keys(o).length>0)for(const l in o)Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>o[l]});Object.defineProperty(i,"$el",{enumerable:!0,configurable:!0,get:()=>e.vnode.el}),e.exposed=i;function r(l){t.value=l,l&&(Object.defineProperty(i,"$el",{enumerable:!0,configurable:!0,get:()=>l instanceof Element?l:l.$el}),e.exposed=i)}return{forwardRef:r,currentRef:t,currentElement:n}}function wo(e,t){const n=uo(!1,300),o=P(null),i=oo();function r(){o.value=null,n.value=!1}function l(s,u){const d=s.currentTarget,a={x:s.clientX,y:s.clientY},c=bo(a,d.getBoundingClientRect()),v=xo(a,c),f=Co(u.getBoundingClientRect()),p=Ao([...v,...f]);o.value=p,n.value=!0}return Q(s=>{if(e.value&&t.value){const u=a=>l(a,t.value),d=a=>l(a,e.value);e.value.addEventListener("pointerleave",u),t.value.addEventListener("pointerleave",d),s(()=>{var a,c;(a=e.value)==null||a.removeEventListener("pointerleave",u),(c=t.value)==null||c.removeEventListener("pointerleave",d)})}}),Q(s=>{var u;if(o.value){const d=a=>{var c,v;if(!o.value)return;const f=a.target,p={x:a.clientX,y:a.clientY},g=((c=e.value)==null?void 0:c.contains(f))||((v=t.value)==null?void 0:v.contains(f)),m=!Oo(p,o.value),h=!!f.closest("[data-grace-area-trigger]");g?r():(m||h)&&(r(),i.trigger())};(u=e.value)==null||u.ownerDocument.addEventListener("pointermove",d),s(()=>{var a;return(a=e.value)==null?void 0:a.ownerDocument.removeEventListener("pointermove",d)})}}),{isPointerInTransit:n,onPointerExit:i.on}}function bo(e,t){const n=Math.abs(t.top-e.y),o=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),r=Math.abs(t.left-e.x);switch(Math.min(n,o,i,r)){case r:return"left";case i:return"right";case n:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function xo(e,t,n=5){const o=[];switch(t){case"top":o.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":o.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":o.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":o.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return o}function Co(e){const{top:t,right:n,bottom:o,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:o},{x:i,y:o}]}function Oo(e,t){const{x:n,y:o}=e;let i=!1;for(let r=0,l=t.length-1;ro!=a>o&&n<(d-s)*(o-u)/(a-u)+s&&(i=!i)}return i}function Ao(e){const t=e.slice();return t.sort((n,o)=>n.xo.x?1:n.yo.y?1:0),Eo(t)}function Eo(e){if(e.length<=1)return e.slice();const t=[];for(let o=0;o=2;){const r=t[t.length-1],l=t[t.length-2];if((r.x-l.x)*(i.y-l.y)>=(r.y-l.y)*(i.x-l.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let o=e.length-1;o>=0;o--){const i=e[o];for(;n.length>=2;){const r=n[n.length-1],l=n[n.length-2];if((r.x-l.x)*(i.y-l.y)>=(r.y-l.y)*(i.x-l.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}let Po=0;function To(e,t="radix"){const n=ho({useId:void 0});return st?`${t}-${st()}`:n.useId?`${t}-${n.useId()}`:`${t}-${++Po}`}function Do(e){const t=P(),n=O(()=>{var i;return((i=t.value)==null?void 0:i.width)??0}),o=O(()=>{var i;return((i=t.value)==null?void 0:i.height)??0});return $e(()=>{const i=He(e);if(i){t.value={width:i.offsetWidth,height:i.offsetHeight};const r=new ResizeObserver(l=>{if(!Array.isArray(l)||!l.length)return;const s=l[0];let u,d;if("borderBoxSize"in s){const a=s.borderBoxSize,c=Array.isArray(a)?a[0]:a;u=c.inlineSize,d=c.blockSize}else u=i.offsetWidth,d=i.offsetHeight;t.value={width:u,height:d}});return r.observe(i,{box:"border-box"}),()=>r.unobserve(i)}else t.value=void 0}),{width:n,height:o}}function _o(e,t){const n=P(e);function o(i){return t[n.value][i]??n.value}return{state:n,dispatch:i=>{n.value=o(i)}}}const Ro=_({name:"PrimitiveSlot",inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{var o,i;if(!n.default)return null;const r=rt(n.default()),l=r.findIndex(a=>a.type!==At);if(l===-1)return r;const s=r[l];(o=s.props)==null||delete o.ref;const u=s.props?se(t,s.props):t;t.class&&(i=s.props)!=null&&i.class&&delete s.props.class;const d=qt(s,u);for(const a in u)a.startsWith("on")&&(d.props||(d.props={}),d.props[a]=u[a]);return r.length===1?d:(r[l]=d,r)}}}),ye=_({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(e,{attrs:t,slots:n}){const o=e.asChild?"template":e.as;return typeof o=="string"&&["area","img","input"].includes(o)?()=>Pe(o,t):o!=="template"?()=>Pe(e.as,t,{default:n.default}):()=>Pe(Ro,t,{default:n.default})}});function So(e,t){var n;const o=P({}),i=P("none"),r=P(e),l=e.value?"mounted":"unmounted";let s;const u=((n=t.value)==null?void 0:n.ownerDocument.defaultView)??it,{state:d,dispatch:a}=_o(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}}),c=m=>{var h;if(Oe){const b=new CustomEvent(m,{bubbles:!1,cancelable:!1});(h=t.value)==null||h.dispatchEvent(b)}};K(e,async(m,h)=>{var b;const y=h!==m;if(await Be(),y){const C=i.value,x=Ee(t.value);m?(a("MOUNT"),c("enter"),x==="none"&&c("after-enter")):x==="none"||((b=o.value)==null?void 0:b.display)==="none"?(a("UNMOUNT"),c("leave"),c("after-leave")):h&&C!==x?(a("ANIMATION_OUT"),c("leave")):(a("UNMOUNT"),c("after-leave"))}},{immediate:!0});const v=m=>{const h=Ee(t.value),b=h.includes(m.animationName),y=d.value==="mounted"?"enter":"leave";if(m.target===t.value&&b&&(c(`after-${y}`),a("ANIMATION_END"),!r.value)){const C=t.value.style.animationFillMode;t.value.style.animationFillMode="forwards",s=u==null?void 0:u.setTimeout(()=>{var x;((x=t.value)==null?void 0:x.style.animationFillMode)==="forwards"&&(t.value.style.animationFillMode=C)})}m.target===t.value&&h==="none"&&a("ANIMATION_END")},f=m=>{m.target===t.value&&(i.value=Ee(t.value))},p=K(t,(m,h)=>{m?(o.value=getComputedStyle(m),m.addEventListener("animationstart",f),m.addEventListener("animationcancel",v),m.addEventListener("animationend",v)):(a("ANIMATION_END"),s!==void 0&&(u==null||u.clearTimeout(s)),h==null||h.removeEventListener("animationstart",f),h==null||h.removeEventListener("animationcancel",v),h==null||h.removeEventListener("animationend",v))},{immediate:!0}),g=K(d,()=>{const m=Ee(t.value);i.value=d.value==="mounted"?m:"none"});return nn(()=>{p(),g()}),{isPresent:O(()=>["mounted","unmountSuspended"].includes(d.value))}}function Ee(e){return e&&getComputedStyle(e).animationName||"none"}const $o=_({name:"Presence",props:{present:{type:Boolean,required:!0},forceMount:{type:Boolean}},slots:{},setup(e,{slots:t,expose:n}){var o;const{present:i,forceMount:r}=xt(e),l=P(),{isPresent:s}=So(i,l);n({present:s});let u=t.default({present:s});u=rt(u||[]);const d=he();if(u&&(u==null?void 0:u.length)>1){const a=(o=d==null?void 0:d.parent)!=null&&o.type.name?`<${d.parent.type.name} />`:"component";throw new Error([`Detected an invalid children for \`${a}\` for \`Presence\` component.`,"","Note: Presence works similarly to `v-if` directly, but it waits for animation/transition to finished before unmounting. So it expect only one direct child of valid VNode type.","You can apply a few solutions:",["Provide a single child element so that `presence` directive attach correctly.","Ensure the first child is an actual element instead of a raw text node or comment node."].map(c=>` - ${c}`).join(` `)].join(` `))}return()=>r.value||i.value||s.value?Pe(t.default({present:s})[0],{ref:a=>{const c=He(a);return typeof(c==null?void 0:c.hasAttribute)>"u"||(c!=null&&c.hasAttribute("data-radix-popper-content-wrapper")?l.value=c.firstElementChild:l.value=c),c}}):null}}),Bo=_({__name:"Teleport",props:{to:{default:"body"},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const t=po();return(n,o)=>w(t)||n.forceMount?($(),M(Kt,{key:0,to:n.to,disabled:n.disabled},[B(n.$slots,"default")],8,["to","disabled"])):Ot("",!0)}}),Lo="dismissableLayer.pointerDownOutside",ko="dismissableLayer.focusOutside";function Ht(e,t){const n=t.closest("[data-dismissable-layer]"),o=e.dataset.dismissableLayer===""?e:e.querySelector("[data-dismissable-layer]"),i=Array.from(e.ownerDocument.querySelectorAll("[data-dismissable-layer]"));return!!(n&&o===n||i.indexOf(o){});return Q(l=>{if(!Oe)return;const s=async d=>{const a=d.target;if(t!=null&&t.value){if(Ht(t.value,a)){i.value=!1;return}if(d.target&&!i.value){let c=function(){Mt(Lo,e,v)};const v={originalEvent:d};d.pointerType==="touch"?(o.removeEventListener("click",r.value),r.value=c,o.addEventListener("click",r.value,{once:!0})):c()}else o.removeEventListener("click",r.value);i.value=!1}},u=window.setTimeout(()=>{o.addEventListener("pointerdown",s)},0);l(()=>{window.clearTimeout(u),o.removeEventListener("pointerdown",s),o.removeEventListener("click",r.value)})}),{onPointerDownCapture:()=>i.value=!0}}function No(e,t){var n;const o=((n=t==null?void 0:t.value)==null?void 0:n.ownerDocument)??(globalThis==null?void 0:globalThis.document),i=P(!1);return Q(r=>{if(!Oe)return;const l=async s=>{t!=null&&t.value&&(await Be(),!(!t.value||Ht(t.value,s.target))&&s.target&&!i.value&&Mt(ko,e,{originalEvent:s}))};o.addEventListener("focusin",l),r(()=>o.removeEventListener("focusin",l))}),{onFocusCapture:()=>i.value=!0,onBlurCapture:()=>i.value=!1}}const J=tn({layersRoot:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Fo=_({__name:"DismissableLayer",props:{disableOutsidePointerEvents:{type:Boolean,default:!1},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","dismiss"],setup(e,{emit:t}){const n=e,o=t,{forwardRef:i,currentElement:r}=I(),l=O(()=>{var p;return((p=r.value)==null?void 0:p.ownerDocument)??globalThis.document}),s=O(()=>J.layersRoot),u=O(()=>r.value?Array.from(s.value).indexOf(r.value):-1),d=O(()=>J.layersWithOutsidePointerEventsDisabled.size>0),a=O(()=>{const p=Array.from(s.value),[g]=[...J.layersWithOutsidePointerEventsDisabled].slice(-1),m=p.indexOf(g);return u.value>=m}),c=Mo(async p=>{const g=[...J.branches].some(m=>m==null?void 0:m.contains(p.target));!a.value||g||(o("pointerDownOutside",p),o("interactOutside",p),await Be(),p.defaultPrevented||o("dismiss"))},r),v=No(p=>{[...J.branches].some(g=>g==null?void 0:g.contains(p.target))||(o("focusOutside",p),o("interactOutside",p),p.defaultPrevented||o("dismiss"))},r);fo("Escape",p=>{u.value===s.value.size-1&&(o("escapeKeyDown",p),p.defaultPrevented||o("dismiss"))});let f;return Q(p=>{r.value&&(n.disableOutsidePointerEvents&&(J.layersWithOutsidePointerEventsDisabled.size===0&&(f=l.value.body.style.pointerEvents,l.value.body.style.pointerEvents="none"),J.layersWithOutsidePointerEventsDisabled.add(r.value)),s.value.add(r.value),p(()=>{n.disableOutsidePointerEvents&&J.layersWithOutsidePointerEventsDisabled.size===1&&(l.value.body.style.pointerEvents=f)}))}),Q(p=>{p(()=>{r.value&&(s.value.delete(r.value),J.layersWithOutsidePointerEventsDisabled.delete(r.value))})}),(p,g)=>($(),M(w(ye),{ref:w(i),"as-child":p.asChild,as:p.as,"data-dismissable-layer":"",style:Le({pointerEvents:d.value?a.value?"auto":"none":void 0}),onFocusCapture:w(v).onFocusCapture,onBlurCapture:w(v).onBlurCapture,onPointerdownCapture:w(c).onPointerDownCapture},{default:D(()=>[B(p.$slots,"default")]),_:3},8,["as-child","as","style","onFocusCapture","onBlurCapture","onPointerdownCapture"]))}});io(()=>P([]));const[Wt,Ho]=Ce("PopperRoot"),Wo=_({inheritAttrs:!1,__name:"PopperRoot",setup(e){const t=P();return Ho({anchor:t,onAnchorChange:n=>t.value=n}),(n,o)=>B(n.$slots,"default")}}),Io=_({__name:"PopperAnchor",props:{element:{},asChild:{type:Boolean},as:{}},setup(e){const t=e,{forwardRef:n,currentElement:o}=I(),i=Wt();return Q(()=>{i.onAnchorChange(t.element??o.value)}),(r,l)=>($(),M(w(ye),{ref:w(n),as:r.as,"as-child":r.asChild},{default:D(()=>[B(r.$slots,"default")]),_:3},8,["as","as-child"]))}});function zo(e){return e!==null}function Vo(e){return{name:"transformOrigin",options:e,fn(t){var n,o,i;const{placement:r,rects:l,middlewareData:s}=t,u=((n=s.arrow)==null?void 0:n.centerOffset)!==0,d=u?0:e.arrowWidth,a=u?0:e.arrowHeight,[c,v]=Ke(r),f={start:"0%",center:"50%",end:"100%"}[v],p=(((o=s.arrow)==null?void 0:o.x)??0)+d/2,g=(((i=s.arrow)==null?void 0:i.y)??0)+a/2;let m="",h="";return c==="bottom"?(m=u?f:`${p}px`,h=`${-a}px`):c==="top"?(m=u?f:`${p}px`,h=`${l.floating.height+a}px`):c==="right"?(m=`${-a}px`,h=u?f:`${g}px`):c==="left"&&(m=`${l.floating.width+a}px`,h=u?f:`${g}px`),{data:{x:m,y:h}}}}}function Ke(e){const[t,n="center"]=e.split("-");return[t,n]}const jo={side:"bottom",sideOffset:0,align:"center",alignOffset:0,arrowPadding:0,avoidCollisions:!0,collisionBoundary:()=>[],collisionPadding:0,sticky:"partial",hideWhenDetached:!1,updatePositionStrategy:"optimized",prioritizePosition:!1},[Uo,Yo]=Ce("PopperContent"),Ko=_({inheritAttrs:!1,__name:"PopperContent",props:Zt({side:{},sideOffset:{},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean},updatePositionStrategy:{},prioritizePosition:{type:Boolean},asChild:{type:Boolean},as:{}},{...jo}),emits:["placed"],setup(e,{emit:t}){const n=e,o=t,i=Wt(),{forwardRef:r,currentElement:l}=I(),s=P(),u=P(),{width:d,height:a}=Do(u),c=O(()=>n.side+(n.align!=="center"?`-${n.align}`:"")),v=O(()=>typeof n.collisionPadding=="number"?n.collisionPadding:{top:0,right:0,bottom:0,left:0,...n.collisionPadding}),f=O(()=>Array.isArray(n.collisionBoundary)?n.collisionBoundary:[n.collisionBoundary]),p=O(()=>({padding:v.value,boundary:f.value.filter(zo),altBoundary:f.value.length>0})),g=no(()=>[Yn({mainAxis:n.sideOffset+a.value,alignmentAxis:n.alignOffset}),n.prioritizePosition&&n.avoidCollisions&&vt({...p.value}),n.avoidCollisions&&Kn({mainAxis:!0,crossAxis:!!n.prioritizePosition,limiter:n.sticky==="partial"?Jn():void 0,...p.value}),!n.prioritizePosition&&n.avoidCollisions&&vt({...p.value}),Xn({...p.value,apply:({elements:E,rects:z,availableWidth:k,availableHeight:F})=>{const{width:S,height:te}=z.reference,N=E.floating.style;N.setProperty("--radix-popper-available-width",`${k}px`),N.setProperty("--radix-popper-available-height",`${F}px`),N.setProperty("--radix-popper-anchor-width",`${S}px`),N.setProperty("--radix-popper-anchor-height",`${te}px`)}}),u.value&&eo({element:u.value,padding:n.arrowPadding}),Vo({arrowWidth:d.value,arrowHeight:a.value}),n.hideWhenDetached&&Gn({strategy:"referenceHidden",...p.value})]),{floatingStyles:m,placement:h,isPositioned:b,middlewareData:y}=to(i.anchor,s,{strategy:"fixed",placement:c,whileElementsMounted:(...E)=>Un(...E,{animationFrame:n.updatePositionStrategy==="always"}),middleware:g}),C=O(()=>Ke(h.value)[0]),x=O(()=>Ke(h.value)[1]);en(()=>{b.value&&o("placed")});const T=O(()=>{var E;return((E=y.value.arrow)==null?void 0:E.centerOffset)!==0}),A=P("");Q(()=>{l.value&&(A.value=window.getComputedStyle(l.value).zIndex)});const R=O(()=>{var E;return((E=y.value.arrow)==null?void 0:E.x)??0}),L=O(()=>{var E;return((E=y.value.arrow)==null?void 0:E.y)??0});return Yo({placedSide:C,onArrowChange:E=>u.value=E,arrowX:R,arrowY:L,shouldHideArrow:T}),(E,z)=>{var k,F,S;return $(),De("div",{ref_key:"floatingRef",ref:s,"data-radix-popper-content-wrapper":"",style:Le({...w(m),transform:w(b)?w(m).transform:"translate(0, -200%)",minWidth:"max-content",zIndex:A.value,"--radix-popper-transform-origin":[(k=w(y).transformOrigin)==null?void 0:k.x,(F=w(y).transformOrigin)==null?void 0:F.y].join(" "),...((S=w(y).hide)==null?void 0:S.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}})},[Y(w(ye),se({ref:w(r)},E.$attrs,{"as-child":n.asChild,as:E.as,"data-side":C.value,"data-align":x.value,style:{animation:w(b)?void 0:"none"}}),{default:D(()=>[B(E.$slots,"default")]),_:3},16,["as-child","as","data-side","data-align","style"])],4)}}}),Xo=fe("polygon",{points:"0,0 30,0 15,10"},null,-1),Go=_({__name:"Arrow",props:{width:{default:10},height:{default:5},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const t=e;return I(),(n,o)=>($(),M(w(ye),se(t,{width:n.width,height:n.height,viewBox:n.asChild?void 0:"0 0 30 10",preserveAspectRatio:n.asChild?void 0:"none"}),{default:D(()=>[B(n.$slots,"default",{},()=>[Xo])]),_:3},16,["width","height","viewBox","preserveAspectRatio"]))}}),qo={top:"bottom",right:"left",bottom:"top",left:"right"},Jo=_({inheritAttrs:!1,__name:"PopperArrow",props:{width:{},height:{},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const{forwardRef:t}=I(),n=Uo(),o=O(()=>qo[n.placedSide.value]);return(i,r)=>{var l,s,u,d;return $(),De("span",{ref:a=>{w(n).onArrowChange(a)},style:Le({position:"absolute",left:(l=w(n).arrowX)!=null&&l.value?`${(s=w(n).arrowX)==null?void 0:s.value}px`:void 0,top:(u=w(n).arrowY)!=null&&u.value?`${(d=w(n).arrowY)==null?void 0:d.value}px`:void 0,[o.value]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[w(n).placedSide.value],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[w(n).placedSide.value],visibility:w(n).shouldHideArrow.value?"hidden":void 0})},[Y(Go,se(i.$attrs,{ref:w(t),style:{display:"block"},as:i.as,"as-child":i.asChild,width:i.width,height:i.height}),{default:D(()=>[B(i.$slots,"default")]),_:3},16,["as","as-child","width","height"])],4)}}}),Qo=_({__name:"VisuallyHidden",props:{asChild:{type:Boolean},as:{default:"span"}},setup(e){return I(),(t,n)=>($(),M(w(ye),{as:t.as,"as-child":t.asChild,style:{position:"absolute",border:0,width:"1px",display:"inline-block",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}},{default:D(()=>[B(t.$slots,"default")]),_:3},8,["as","as-child"]))}});function Zo(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}Zo();const It="tooltip.open",[lt,ei]=Ce("TooltipProvider"),ti=_({inheritAttrs:!1,__name:"TooltipProvider",props:{delayDuration:{default:700},skipDelayDuration:{default:300},disableHoverableContent:{type:Boolean,default:!1},disableClosingTrigger:{type:Boolean},disabled:{type:Boolean},ignoreNonKeyboardFocus:{type:Boolean,default:!1}},setup(e){const t=e,{delayDuration:n,skipDelayDuration:o,disableHoverableContent:i,disableClosingTrigger:r,ignoreNonKeyboardFocus:l,disabled:s}=xt(t);I();const u=P(!0),d=P(!1),{start:a,stop:c}=Nt(()=>{u.value=!0},o,{immediate:!1});return ei({isOpenDelayed:u,delayDuration:n,onOpen(){c(),u.value=!1},onClose(){a()},isPointerInTransitRef:d,disableHoverableContent:i,disableClosingTrigger:r,disabled:s,ignoreNonKeyboardFocus:l}),(v,f)=>B(v.$slots,"default")}}),[We,ni]=Ce("TooltipRoot"),oi=_({__name:"TooltipRoot",props:{defaultOpen:{type:Boolean,default:!1},open:{type:Boolean,default:void 0},delayDuration:{default:void 0},disableHoverableContent:{type:Boolean,default:void 0},disableClosingTrigger:{type:Boolean,default:void 0},disabled:{type:Boolean,default:void 0},ignoreNonKeyboardFocus:{type:Boolean,default:void 0}},emits:["update:open"],setup(e,{emit:t}){const n=e,o=t;I();const i=lt(),r=O(()=>n.disableHoverableContent??i.disableHoverableContent.value),l=O(()=>n.disableClosingTrigger??i.disableClosingTrigger.value),s=O(()=>n.disabled??i.disabled.value),u=O(()=>n.delayDuration??i.delayDuration.value),d=O(()=>n.ignoreNonKeyboardFocus??i.ignoreNonKeyboardFocus.value),a=mo(n,"open",o,{defaultValue:n.defaultOpen,passive:n.open===void 0});K(a,y=>{i.onClose&&(y?(i.onOpen(),document.dispatchEvent(new CustomEvent(It))):i.onClose())});const c=P(!1),v=P(),f=O(()=>a.value?c.value?"delayed-open":"instant-open":"closed"),{start:p,stop:g}=Nt(()=>{c.value=!0,a.value=!0},u,{immediate:!1});function m(){g(),c.value=!1,a.value=!0}function h(){g(),a.value=!1}function b(){p()}return ni({contentId:"",open:a,stateAttribute:f,trigger:v,onTriggerChange(y){v.value=y},onTriggerEnter(){i.isOpenDelayed.value?b():m()},onTriggerLeave(){r.value?h():g()},onOpen:m,onClose:h,disableHoverableContent:r,disableClosingTrigger:l,disabled:s,ignoreNonKeyboardFocus:d}),(y,C)=>($(),M(w(Wo),null,{default:D(()=>[B(y.$slots,"default",{open:w(a)})]),_:3}))}}),ii=_({__name:"TooltipTrigger",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const t=e,n=We(),o=lt();n.contentId||(n.contentId=To(void 0,"radix-vue-tooltip-content"));const{forwardRef:i,currentElement:r}=I(),l=P(!1),s=P(!1),u=O(()=>n.disabled.value?{}:{click:g,focus:f,pointermove:c,pointerleave:v,pointerdown:a,blur:p});$e(()=>{n.onTriggerChange(r.value)});function d(){setTimeout(()=>{l.value=!1},1)}function a(){l.value=!0,document.addEventListener("pointerup",d,{once:!0})}function c(m){m.pointerType!=="touch"&&!s.value&&!o.isPointerInTransitRef.value&&(n.onTriggerEnter(),s.value=!0)}function v(){n.onTriggerLeave(),s.value=!1}function f(m){var h,b;l.value||n.ignoreNonKeyboardFocus.value&&!((b=(h=m.target).matches)!=null&&b.call(h,":focus-visible"))||n.onOpen()}function p(){n.onClose()}function g(){n.disableClosingTrigger.value||n.onClose()}return(m,h)=>($(),M(w(Io),{"as-child":""},{default:D(()=>[Y(w(ye),se({ref:w(i),"aria-describedby":w(n).open.value?w(n).contentId:void 0,"data-state":w(n).stateAttribute.value,as:m.as,"as-child":t.asChild,"data-grace-area-trigger":""},jt(u.value)),{default:D(()=>[B(m.$slots,"default")]),_:3},16,["aria-describedby","data-state","as","as-child"])]),_:3}))}}),zt=_({__name:"TooltipContentImpl",props:{ariaLabel:{},asChild:{type:Boolean},as:{},side:{default:"top"},sideOffset:{default:0},align:{default:"center"},alignOffset:{},avoidCollisions:{type:Boolean,default:!0},collisionBoundary:{default:()=>[]},collisionPadding:{default:0},arrowPadding:{default:0},sticky:{default:"partial"},hideWhenDetached:{type:Boolean,default:!1}},emits:["escapeKeyDown","pointerDownOutside"],setup(e,{emit:t}){const n=e,o=t,i=We(),{forwardRef:r}=I(),l=Xt(),s=O(()=>{var a;return(a=l.default)==null?void 0:a.call(l)}),u=O(()=>{var a;if(n.ariaLabel)return n.ariaLabel;let c="";function v(f){typeof f.children=="string"&&f.type!==At?c+=f.children:Array.isArray(f.children)&&f.children.forEach(p=>v(p))}return(a=s.value)==null||a.forEach(f=>v(f)),c}),d=O(()=>{const{ariaLabel:a,...c}=n;return c});return $e(()=>{Ye(window,"scroll",a=>{const c=a.target;c!=null&&c.contains(i.trigger.value)&&i.onClose()}),Ye(window,It,i.onClose)}),(a,c)=>($(),M(w(Fo),{"as-child":"","disable-outside-pointer-events":!1,onEscapeKeyDown:c[0]||(c[0]=v=>o("escapeKeyDown",v)),onPointerDownOutside:c[1]||(c[1]=v=>{var f;w(i).disableClosingTrigger.value&&(f=w(i).trigger.value)!=null&&f.contains(v.target)&&v.preventDefault(),o("pointerDownOutside",v)}),onFocusOutside:c[2]||(c[2]=Gt(()=>{},["prevent"])),onDismiss:c[3]||(c[3]=v=>w(i).onClose())},{default:D(()=>[Y(w(Ko),se({ref:w(r),"data-state":w(i).stateAttribute.value},{...a.$attrs,...d.value},{style:{"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"}}),{default:D(()=>[B(a.$slots,"default"),Y(w(Qo),{id:w(i).contentId,role:"tooltip"},{default:D(()=>[Xe(Ge(u.value),1)]),_:1},8,["id"])]),_:3},16,["data-state"])]),_:3}))}}),ri=_({__name:"TooltipContentHoverable",props:{ariaLabel:{},asChild:{type:Boolean},as:{},side:{},sideOffset:{},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean}},setup(e){const t=Ft(e),{forwardRef:n,currentElement:o}=I(),{trigger:i,onClose:r}=We(),l=lt(),{isPointerInTransit:s,onPointerExit:u}=wo(i,o);return l.isPointerInTransitRef=s,u(()=>{r()}),(d,a)=>($(),M(zt,se({ref:w(n)},w(t)),{default:D(()=>[B(d.$slots,"default")]),_:3},16))}}),li=_({__name:"TooltipContent",props:{forceMount:{type:Boolean},ariaLabel:{},asChild:{type:Boolean},as:{},side:{default:"top"},sideOffset:{},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean}},emits:["escapeKeyDown","pointerDownOutside"],setup(e,{emit:t}){const n=e,o=t,i=We(),r=yo(n,o),{forwardRef:l}=I();return(s,u)=>($(),M(w($o),{present:s.forceMount||w(i).open.value},{default:D(()=>[($(),M(Ut(w(i).disableHoverableContent.value?zt:ri),se({ref:w(l)},w(r)),{default:D(()=>[B(s.$slots,"default")]),_:3},16))]),_:3},8,["present"]))}}),si=_({__name:"TooltipArrow",props:{width:{default:10},height:{default:5},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const t=e;return I(),(n,o)=>($(),M(w(Jo),wt(bt(t)),{default:D(()=>[B(n.$slots,"default")]),_:3},16))}}),ai=_({__name:"TooltipPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const t=e;return(n,o)=>($(),M(w(Bo),wt(bt(t)),{default:D(()=>[B(n.$slots,"default")]),_:3},16))}}),ui={key:0,flex:"","gap-2":""},hi=_({__name:"ColorPalette",props:{colors:null},setup(e){const t=sn();return(n,o)=>e.colors.length?($(),De("div",ui,[($(!0),De(Pt,null,an(e.colors,({hex:i,name:r})=>($(),M(w(ti),{key:i||"default"},{default:D(()=>[Y(w(oi),null,{default:D(()=>[Y(w(ii),{transition:"all ease-in-out duration-250","bg-primary-500":"","size-6":"","cursor-pointer":"","rounded-full":"",style:Le(i?{background:i}:{"--theme-colors-hue":w(un)}),class:Te(w(t).isColorSelectedForPrimary(i)?"scale-150 mx-1":"hover:scale-110"),onClick:l=>w(t).applyPrimaryColorFrom(i)},null,8,["style","class","onClick"]),Y(w(ai),null,{default:D(()=>[Y(w(li),{bg:"white dark:neutral-800","rounded-lg":"","px-3":"","py-1.5":"","text-sm":"","shadow-md":""},{default:D(()=>[Xe(Ge(r)+" ",1),Y(w(si),{"fill-white":"","dark:fill-neutral-800":""})]),_:2},1024)]),_:2},1024)]),_:2},1024)]),_:2},1024))),128))])):Ot("",!0)}}),ci=["onClick"],di={flex:"","gap-1.5":""},gi=_({__name:"Section",props:{title:null,icon:null,innerClass:null},setup(e){return(t,n)=>($(),M(w(cn),{default:""},{trigger:D(o=>[fe("button",{class:"setting-bar",bg:"zinc-100 dark:zinc-800",hover:"bg-zinc-200 dark:bg-zinc-700",onClick:i=>o.setVisible(!o.visible)},[fe("div",di,[fe("div",{class:Te(e.icon),"size-6":""},null,2),Xe(" "+Ge(t.$t(e.title)),1)]),fe("div",{"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-250",class:Te({"rotate-180":o.visible})},null,2)],8,ci)]),default:D(()=>[fe("div",{grid:"","gap-4":"","p-4":"",class:Te(e.innerClass)},[B(t.$slots,"default")],2)]),_:3}))}});export{gi as _,hi as a}; diff --git a/assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-UpCqB8UJ.js b/assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-CgsOdTr3.js similarity index 96% rename from assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-UpCqB8UJ.js rename to assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-CgsOdTr3.js index e68e1238280605aea96402159939b00b1acdb272..2ded910615297d0d0f7b54ce4a79c3de190def65 100644 --- a/assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-UpCqB8UJ.js +++ b/assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-CgsOdTr3.js @@ -1 +1 @@ -import{d as N,i as E,h as R,bw as ie,c as h,o as d,p as U,a as t,z as Y,A as q,C as V,D as k,g as x,w as j,H as Z,b as M,e,bJ as G,bI as H,bx as J,by as Q,bE as re,s as ne,m as de,x as I,y as K,bS as W,bT as X,bN as ue,bF as ve,bG as T}from"./index-rD0Uu1v9.js";import{b as pe,a as ee,_ as C}from"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js";import"./live2d-zip-loader-BdiFCiUD.js";import{u as ce,g as me}from"./speech-CUKri9wm.js";import{u as fe}from"./providers-Dg3FpvfZ.js";import{_ as ge,a as be}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as ye}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as xe,a as he}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";const ke={flex:"~ row",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250,"mb-6":"","items-center":"","gap-3":""},Se={relative:""},Ve={key:0,absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},we={text:"neutral-300 dark:neutral-500","text-nowrap":""},Ue={"text-nowrap":"","text-3xl":"","font-semibold":""},$e={key:0,"text-sm":"",text:"neutral-500 dark:neutral-400"},_e={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},Be=N({__name:"ProviderSettingsLayout2",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function},title:null,subtitle:null,categoryLabel:null},emits:["back"],setup(a,{emit:i}){const b=a,c=i,{t:y}=E(),w=R(()=>b.title||b.providerName||""),s=R(()=>b.categoryLabel||y("settings.pages.providers.title"));function f(){b.onBack&&b.onBack(),c("back")}return(l,v)=>{const r=ie("motion");return d(),h("div",null,[U(l.$slots,"header",{},()=>[q((d(),h("div",ke,[U(l.$slots,"backButton",{},()=>[t("button",{onClick:f},v[0]||(v[0]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)]))]),t("div",null,[U(l.$slots,"title",{},()=>[t("h1",Se,[s.value?(d(),h("div",Ve,[t("span",we,k(s.value),1)])):V("",!0),t("div",Ue,k(w.value),1)])]),U(l.$slots,"subtitle",{},()=>[a.subtitle?(d(),h("div",$e,k(a.subtitle),1)):V("",!0)])]),U(l.$slots,"headerExtra")])),[[r]])]),U(l.$slots,"default"),t("div",_e,[t("div",{text:"40",class:Y(a.providerIcon||a.providerIconColor)},null,2)])])}}}),Ie={"w-full":"","rounded-xl":""},Le={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},Te={class:"inline-flex items-center gap-4"},Me={flex:"~ col gap-4"},Pe=["placeholder"],Ce=["placeholder"],Re={flex:"~ col gap-6"},Oe={grid:"~ cols-2 gap-4"},qe={class:"flex items-center gap-1 text-sm font-medium"},ze={class:"text-xs text-neutral-500 dark:text-neutral-400"},Ke=["value"],Ne={grid:"~ cols-2 gap-4"},Ee={class:"flex items-center gap-1 text-sm font-medium"},Fe={class:"text-xs text-neutral-500 dark:text-neutral-400"},je=["value"],De={flex:"~ row","gap-4":""},Ae=["disabled"],Ge={flex:"~ row","items-center":"","gap-2":""},He={flex:"~ row","items-center":"","gap-2":""},Je={key:2,class:"mt-2 text-sm text-red-500"},Qe={key:3,class:"mt-2 text-sm text-red-500"},We={key:4,class:"mt-2 text-sm text-red-500"},Xe=["src"],ct=N({__name:"SpeechPlayground",props:{defaultText:null,availableVoices:null,availableLanguages:null,generateSpeech:{type:Function},apiKeyConfigured:{type:Boolean}},setup(a,{expose:i}){const b=a,{t:c}=E(),y=x(b.defaultText||"Hello! This is a test of the voice synthesis."),w=x(!1),s=x(""),f=x(""),l=x(null),v=x(!1),r=x(""),n=x(b.availableLanguages[0]||"en-US"),g=x("");j(()=>b.availableVoices,S=>{var p;S.length>0&&!g.value&&(g.value=((p=S[0])==null?void 0:p.id)||"")},{immediate:!0});async function P(){if(!(!y.value.trim()&&!v.value||v.value&&!r.value.trim()||!g.value)){w.value=!0,f.value="";try{s.value&&$();const S=v.value?r.value:y.value,p=await b.generateSpeech(S,g.value,v.value);s.value=URL.createObjectURL(new Blob([p])),setTimeout(()=>{l.value&&l.value.play()},100)}catch(S){console.error("Error generating speech:",S),f.value=S instanceof Error?S.message:"An unknown error occurred"}finally{w.value=!1}}}function $(){l.value&&(l.value.pause(),l.value.currentTime=0),s.value&&(URL.revokeObjectURL(s.value),s.value="")}return Z(()=>{s.value&&URL.revokeObjectURL(s.value)}),i({testText:y,ssmlText:r,useSSML:v,selectedLanguage:n,selectedVoice:g,isGenerating:w,audioUrl:s,errorMessage:f,audioPlayer:l,generateTestSpeech:P,stopTestAudio:$}),(S,p)=>(d(),h("div",Ie,[t("h2",Le,[t("div",Te,[M(e(pe)),t("div",null,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),t("div",Me,[M(e(ee),{modelValue:v.value,"onUpdate:modelValue":p[0]||(p[0]=m=>v.value=m),label:e(c)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.label"),description:e(c)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.description")},null,8,["modelValue","label","description"]),v.value?q((d(),h("textarea",{key:1,"onUpdate:modelValue":p[2]||(p[2]=m=>r.value=m),placeholder:e(c)("settings.pages.modules.speech.sections.section.voice-settings.input-ssml.placeholder"),border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-48":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","font-mono":"","outline-none":""},null,8,Ce)),[[G,r.value]]):q((d(),h("textarea",{key:0,"onUpdate:modelValue":p[1]||(p[1]=m=>y.value=m),placeholder:e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.input.placeholder"),border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-24":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","outline-none":""},null,8,Pe)),[[G,y.value]]),t("div",Re,[t("label",Oe,[t("div",null,[t("div",qe,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.language.label")),1),t("div",ze,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.language.description")),1)]),q(t("select",{"onUpdate:modelValue":p[3]||(p[3]=m=>n.value=m),border:"neutral-300 dark:neutral-800 solid 2 focus:neutral-400 dark:focus:neutral-600",transition:"border duration-250 ease-in-out","w-full":"","rounded-lg":"","px-2":"","py-1":"","text-nowrap":"","text-sm":"","outline-none":""},[(d(!0),h(J,null,Q(a.availableLanguages,m=>(d(),h("option",{key:m,value:m},k(m),9,Ke))),128))],512),[[H,n.value]])]),t("label",Ne,[t("div",null,[t("div",Ee,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.label")),1),t("div",Fe,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.description")),1)]),q(t("select",{"onUpdate:modelValue":p[4]||(p[4]=m=>g.value=m),border:"neutral-300 dark:neutral-800 solid 2 focus:neutral-400 dark:focus:neutral-600",transition:"border duration-250 ease-in-out","w-full":"","rounded-lg":"","px-2":"","py-1":"","text-nowrap":"","text-sm":"","outline-none":""},[(d(!0),h(J,null,Q(a.availableVoices,m=>(d(),h("option",{key:m.id,value:m.id},k(m.name),9,je))),128))],512),[[H,g.value]])])]),t("div",De,[t("button",{border:"neutral-800 dark:neutral-200 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"",text:"neutral-100 dark:neutral-900","py-2":"","text-sm":"",disabled:w.value||!y.value.trim()&&!v.value||v.value&&!r.value.trim()||!g.value||!a.apiKeyConfigured,class:Y({"opacity-50 cursor-not-allowed":w.value||!y.value.trim()&&!v.value||v.value&&!r.value.trim()||!g.value||!a.apiKeyConfigured}),bg:"neutral-700 dark:neutral-300",onClick:P},[t("div",Ge,[p[5]||(p[5]=t("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),t("span",null,k(w.value?e(c)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):e(c)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,Ae),s.value?(d(),h("button",{key:0,border:"primary-300 dark:primary-800 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"","py-2":"","text-sm":"",onClick:$},[t("div",He,[p[6]||(p[6]=t("div",{"i-solar:stop-circle-bold-duotone":""},null,-1)),t("span",null,k(e(c)("settings.pages.modules.speech.sections.section.playground.buttons.stop.label")),1)])])):V("",!0)]),a.apiKeyConfigured?V("",!0):(d(),h("div",Je,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.validation.error-missing-api-key")),1)),g.value?V("",!0):(d(),h("div",Qe,k(e(c)("settings.pages.modules.speech.sections.section.playground.select-voice.required")),1)),f.value?(d(),h("div",We,k(f.value),1)):V("",!0),s.value?(d(),h("audio",{key:5,ref_key:"audioPlayer",ref:l,src:s.value,controls:"",class:"mt-2 w-full"},null,8,Xe)):V("",!0)]),U(S.$slots,"default")]))}}),Ye={flex:"~ col md:row gap-6"},Ze={flex:"~ col gap-6"},et={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},tt={flex:"~ col gap-4"},lt={flex:"~ col gap-6",class:"w-full md:w-[60%]"},st={"w-full":"","rounded-xl":""},mt=N({__name:"SpeechProviderSettings",props:{providerId:null,defaultModel:null,additionalSettings:null},setup(a){const i=a,{t:b}=E(),c=re(),y=fe(),w=ce(),{providers:s}=ne(y),f=R(()=>y.getProviderMetadata(i.providerId)),l=R({get:()=>{var o;return((o=s.value[i.providerId])==null?void 0:o.apiKey)||""},set:o=>{s.value[i.providerId]||(s.value[i.providerId]={}),s.value[i.providerId].apiKey=o}}),v=R({get:()=>{var o,u,_;return((o=s.value[i.providerId])==null?void 0:o.baseUrl)||((_=(u=f.value)==null?void 0:u.defaultOptions)==null?void 0:_.baseUrl)||""},set:o=>{s.value[i.providerId]||(s.value[i.providerId]={}),s.value[i.providerId].baseUrl=o}}),r=x("Hello! This is a test of voice synthesis."),n=x(!1),g=x(""),P=x(""),$=x(null),S=x(!1),p=x(""),m=x(""),B=x({});function te(){var o;(o=s.value[i.providerId])!=null&&o.voiceSettings?B.value={...s.value[i.providerId].voiceSettings}:B.value={pitch:0,speed:1,volume:0,...i.additionalSettings}}de(()=>{var o,u,_,L;y.initializeProvider(i.providerId),l.value=((o=s.value[i.providerId])==null?void 0:o.apiKey)||"",v.value=((u=s.value[i.providerId])==null?void 0:u.baseUrl)||((L=(_=f.value)==null?void 0:_.defaultOptions)==null?void 0:L.baseUrl)||"",te(),y.configuredProviders[i.providerId]&&w.loadVoicesForProvider(i.providerId)});const F=ue(()=>{var o,u;s.value[i.providerId]={...s.value[i.providerId],apiKey:l.value,baseUrl:v.value||((u=(o=f.value)==null?void 0:o.defaultOptions)==null?void 0:u.baseUrl)||"",voiceSettings:{...B.value}}},1e3);j([l,v],F),j(B,F,{deep:!0});async function le(){if(!r.value.trim()&&!S.value||S.value&&!p.value.trim())return;const o=y.getProviderInstance(i.providerId);if(!o){console.error("Failed to initialize speech provider");return}if(!m.value){console.error("No active speech voice selected");return}n.value=!0,P.value="";try{g.value&&D();const u=i.defaultModel||"default",_=S.value?p.value:r.value,L=await me({...o.speech(u,{voiceSettings:B.value}),input:_,voice:m.value});g.value=URL.createObjectURL(new Blob([L])),setTimeout(()=>{$.value&&$.value.play()},100)}catch(u){console.error("Error generating speech:",u),P.value=u instanceof Error?u.message:"An unknown error occurred"}finally{n.value=!1}}function D(){$.value&&($.value.pause(),$.value.currentTime=0),g.value&&(URL.revokeObjectURL(g.value),g.value="")}Z(()=>{g.value&&URL.revokeObjectURL(g.value)});function se(){var o,u;B.value={...((u=(o=f.value)==null?void 0:o.defaultOptions)==null?void 0:u.voiceSettings)||{}},F()}function oe(o,u){B.value[o]=u}const A=R(()=>({voiceSettings:B.value,updateVoiceSettings:oe,isGenerating:n.value,testText:r.value,useSSML:S.value,ssmlText:p.value,generateTestSpeech:le,stopTestAudio:D,audioUrl:g.value,audioPlayer:$.value,errorMessage:P.value}));return(o,u)=>{var _,L;return d(),I(Be,{"provider-name":(_=f.value)==null?void 0:_.localizedName,"provider-icon":(L=f.value)==null?void 0:L.icon,"on-back":()=>e(c).back()},{default:K(()=>[t("div",Ye,[M(e(xe),{class:"w-full md:w-[40%]"},{default:K(()=>[M(e(he),{title:e(b)("settings.pages.providers.common.section.basic.title"),description:e(b)("settings.pages.providers.common.section.basic.description"),"on-reset":se},{default:K(()=>{var O;return[M(e(ye),{modelValue:l.value,"onUpdate:modelValue":u[0]||(u[0]=z=>l.value=z),"provider-name":(O=f.value)==null?void 0:O.localizedName,placeholder:"sk-"},null,8,["modelValue","provider-name"]),U(o.$slots,"basic-settings")]}),_:3},8,["title","description"]),t("div",Ze,[t("h2",et,k(e(b)("settings.pages.providers.common.section.voice.title")),1),t("div",tt,[U(o.$slots,"voice-settings",W(X(A.value)))])]),M(e(ge),{title:e(b)("settings.pages.providers.common.section.advanced.title")},{default:K(()=>{var O,z;return[M(e(be),{modelValue:v.value,"onUpdate:modelValue":u[1]||(u[1]=ae=>v.value=ae),placeholder:((z=(O=f.value)==null?void 0:O.defaultOptions)==null?void 0:z.baseUrl)||"",required:""},null,8,["modelValue","placeholder"]),U(o.$slots,"advanced-settings")]}),_:3},8,["title"])]),_:3}),t("div",lt,[t("div",st,[U(o.$slots,"playground",W(X(A.value)))])])])]),_:3},8,["provider-name","provider-icon","on-back"])}}}),ot={flex:"~ col gap-4"},ft=N({__name:"SpeechVoiceSettings",props:ve({settings:null,showPitch:{type:Boolean},showSpeed:{type:Boolean},showStyle:{type:Boolean},showStability:{type:Boolean},showSimilarityBoost:{type:Boolean},showVolume:{type:Boolean},showSpeakerBoost:{type:Boolean}},{pitch:{required:!1,default:0},pitchModifiers:{},speed:{required:!1,default:1},speedModifiers:{},volume:{required:!1,default:0},volumeModifiers:{},style:{required:!1,default:0},styleModifiers:{},stability:{required:!1,default:.5},stabilityModifiers:{},similarityBoost:{required:!1,default:.75},similarityBoostModifiers:{},useSpeakerBoost:{type:Boolean,required:!1,default:!1},useSpeakerBoostModifiers:{}}),emits:["update:pitch","update:speed","update:volume","update:style","update:stability","update:similarityBoost","update:useSpeakerBoost"],setup(a){const i=T(a,"pitch"),b=T(a,"speed"),c=T(a,"volume"),y=T(a,"style"),w=T(a,"stability"),s=T(a,"similarityBoost"),f=T(a,"useSpeakerBoost"),{t:l}=E();return(v,r)=>(d(),h("div",ot,[a.showPitch?(d(),I(e(C),{key:0,modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=n=>i.value=n),label:e(l)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:e(l)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":n=>`${n}%`},null,8,["modelValue","label","description","format-value"])):V("",!0),a.showSpeed?(d(),I(e(C),{key:1,modelValue:b.value,"onUpdate:modelValue":r[1]||(r[1]=n=>b.value=n),label:e(l)("settings.pages.providers.provider.common.fields.field.speed.label"),description:e(l)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showVolume?(d(),I(e(C),{key:2,modelValue:c.value,"onUpdate:modelValue":r[2]||(r[2]=n=>c.value=n),label:e(l)("settings.pages.providers.provider.common.fields.field.volume.label"),description:e(l)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":n=>`${n}%`},null,8,["modelValue","label","description","format-value"])):V("",!0),a.showStyle?(d(),I(e(C),{key:3,modelValue:y.value,"onUpdate:modelValue":r[3]||(r[3]=n=>y.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.style.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.style.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showStability?(d(),I(e(C),{key:4,modelValue:w.value,"onUpdate:modelValue":r[4]||(r[4]=n=>w.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.stability.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.stability.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showSimilarityBoost?(d(),I(e(C),{key:5,modelValue:s.value,"onUpdate:modelValue":r[5]||(r[5]=n=>s.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showSpeakerBoost?(d(),I(e(ee),{key:6,modelValue:f.value,"onUpdate:modelValue":r[6]||(r[6]=n=>f.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.description")},null,8,["modelValue","label","description"])):V("",!0),U(v.$slots,"default")]))}});export{ct as _,ft as a,mt as b}; +import{d as N,i as E,h as R,bw as ie,c as h,o as d,p as U,a as t,z as Y,A as q,C as V,D as k,g as x,w as j,H as Z,b as M,e,bJ as G,bI as H,bx as J,by as Q,bE as re,s as ne,m as de,x as I,y as K,bS as W,bT as X,bN as ue,bF as ve,bG as T}from"./index-Dlp4W1Zl.js";import{b as pe,a as ee,_ as C}from"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js";import"./live2d-zip-loader-C5j9stxV.js";import{u as ce,g as me}from"./speech-DU07zXBj.js";import{u as fe}from"./providers-BRCa7xUS.js";import{_ as ge,a as be}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as ye}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as xe,a as he}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";const ke={flex:"~ row",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250,"mb-6":"","items-center":"","gap-3":""},Se={relative:""},Ve={key:0,absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},we={text:"neutral-300 dark:neutral-500","text-nowrap":""},Ue={"text-nowrap":"","text-3xl":"","font-semibold":""},$e={key:0,"text-sm":"",text:"neutral-500 dark:neutral-400"},_e={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},Be=N({__name:"ProviderSettingsLayout2",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function},title:null,subtitle:null,categoryLabel:null},emits:["back"],setup(a,{emit:i}){const b=a,c=i,{t:y}=E(),w=R(()=>b.title||b.providerName||""),s=R(()=>b.categoryLabel||y("settings.pages.providers.title"));function f(){b.onBack&&b.onBack(),c("back")}return(l,v)=>{const r=ie("motion");return d(),h("div",null,[U(l.$slots,"header",{},()=>[q((d(),h("div",ke,[U(l.$slots,"backButton",{},()=>[t("button",{onClick:f},v[0]||(v[0]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)]))]),t("div",null,[U(l.$slots,"title",{},()=>[t("h1",Se,[s.value?(d(),h("div",Ve,[t("span",we,k(s.value),1)])):V("",!0),t("div",Ue,k(w.value),1)])]),U(l.$slots,"subtitle",{},()=>[a.subtitle?(d(),h("div",$e,k(a.subtitle),1)):V("",!0)])]),U(l.$slots,"headerExtra")])),[[r]])]),U(l.$slots,"default"),t("div",_e,[t("div",{text:"40",class:Y(a.providerIcon||a.providerIconColor)},null,2)])])}}}),Ie={"w-full":"","rounded-xl":""},Le={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},Te={class:"inline-flex items-center gap-4"},Me={flex:"~ col gap-4"},Pe=["placeholder"],Ce=["placeholder"],Re={flex:"~ col gap-6"},Oe={grid:"~ cols-2 gap-4"},qe={class:"flex items-center gap-1 text-sm font-medium"},ze={class:"text-xs text-neutral-500 dark:text-neutral-400"},Ke=["value"],Ne={grid:"~ cols-2 gap-4"},Ee={class:"flex items-center gap-1 text-sm font-medium"},Fe={class:"text-xs text-neutral-500 dark:text-neutral-400"},je=["value"],De={flex:"~ row","gap-4":""},Ae=["disabled"],Ge={flex:"~ row","items-center":"","gap-2":""},He={flex:"~ row","items-center":"","gap-2":""},Je={key:2,class:"mt-2 text-sm text-red-500"},Qe={key:3,class:"mt-2 text-sm text-red-500"},We={key:4,class:"mt-2 text-sm text-red-500"},Xe=["src"],ct=N({__name:"SpeechPlayground",props:{defaultText:null,availableVoices:null,availableLanguages:null,generateSpeech:{type:Function},apiKeyConfigured:{type:Boolean}},setup(a,{expose:i}){const b=a,{t:c}=E(),y=x(b.defaultText||"Hello! This is a test of the voice synthesis."),w=x(!1),s=x(""),f=x(""),l=x(null),v=x(!1),r=x(""),n=x(b.availableLanguages[0]||"en-US"),g=x("");j(()=>b.availableVoices,S=>{var p;S.length>0&&!g.value&&(g.value=((p=S[0])==null?void 0:p.id)||"")},{immediate:!0});async function P(){if(!(!y.value.trim()&&!v.value||v.value&&!r.value.trim()||!g.value)){w.value=!0,f.value="";try{s.value&&$();const S=v.value?r.value:y.value,p=await b.generateSpeech(S,g.value,v.value);s.value=URL.createObjectURL(new Blob([p])),setTimeout(()=>{l.value&&l.value.play()},100)}catch(S){console.error("Error generating speech:",S),f.value=S instanceof Error?S.message:"An unknown error occurred"}finally{w.value=!1}}}function $(){l.value&&(l.value.pause(),l.value.currentTime=0),s.value&&(URL.revokeObjectURL(s.value),s.value="")}return Z(()=>{s.value&&URL.revokeObjectURL(s.value)}),i({testText:y,ssmlText:r,useSSML:v,selectedLanguage:n,selectedVoice:g,isGenerating:w,audioUrl:s,errorMessage:f,audioPlayer:l,generateTestSpeech:P,stopTestAudio:$}),(S,p)=>(d(),h("div",Ie,[t("h2",Le,[t("div",Te,[M(e(pe)),t("div",null,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),t("div",Me,[M(e(ee),{modelValue:v.value,"onUpdate:modelValue":p[0]||(p[0]=m=>v.value=m),label:e(c)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.label"),description:e(c)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.description")},null,8,["modelValue","label","description"]),v.value?q((d(),h("textarea",{key:1,"onUpdate:modelValue":p[2]||(p[2]=m=>r.value=m),placeholder:e(c)("settings.pages.modules.speech.sections.section.voice-settings.input-ssml.placeholder"),border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-48":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","font-mono":"","outline-none":""},null,8,Ce)),[[G,r.value]]):q((d(),h("textarea",{key:0,"onUpdate:modelValue":p[1]||(p[1]=m=>y.value=m),placeholder:e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.input.placeholder"),border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-24":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","outline-none":""},null,8,Pe)),[[G,y.value]]),t("div",Re,[t("label",Oe,[t("div",null,[t("div",qe,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.language.label")),1),t("div",ze,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.language.description")),1)]),q(t("select",{"onUpdate:modelValue":p[3]||(p[3]=m=>n.value=m),border:"neutral-300 dark:neutral-800 solid 2 focus:neutral-400 dark:focus:neutral-600",transition:"border duration-250 ease-in-out","w-full":"","rounded-lg":"","px-2":"","py-1":"","text-nowrap":"","text-sm":"","outline-none":""},[(d(!0),h(J,null,Q(a.availableLanguages,m=>(d(),h("option",{key:m,value:m},k(m),9,Ke))),128))],512),[[H,n.value]])]),t("label",Ne,[t("div",null,[t("div",Ee,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.label")),1),t("div",Fe,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.description")),1)]),q(t("select",{"onUpdate:modelValue":p[4]||(p[4]=m=>g.value=m),border:"neutral-300 dark:neutral-800 solid 2 focus:neutral-400 dark:focus:neutral-600",transition:"border duration-250 ease-in-out","w-full":"","rounded-lg":"","px-2":"","py-1":"","text-nowrap":"","text-sm":"","outline-none":""},[(d(!0),h(J,null,Q(a.availableVoices,m=>(d(),h("option",{key:m.id,value:m.id},k(m.name),9,je))),128))],512),[[H,g.value]])])]),t("div",De,[t("button",{border:"neutral-800 dark:neutral-200 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"",text:"neutral-100 dark:neutral-900","py-2":"","text-sm":"",disabled:w.value||!y.value.trim()&&!v.value||v.value&&!r.value.trim()||!g.value||!a.apiKeyConfigured,class:Y({"opacity-50 cursor-not-allowed":w.value||!y.value.trim()&&!v.value||v.value&&!r.value.trim()||!g.value||!a.apiKeyConfigured}),bg:"neutral-700 dark:neutral-300",onClick:P},[t("div",Ge,[p[5]||(p[5]=t("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),t("span",null,k(w.value?e(c)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):e(c)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,Ae),s.value?(d(),h("button",{key:0,border:"primary-300 dark:primary-800 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"","py-2":"","text-sm":"",onClick:$},[t("div",He,[p[6]||(p[6]=t("div",{"i-solar:stop-circle-bold-duotone":""},null,-1)),t("span",null,k(e(c)("settings.pages.modules.speech.sections.section.playground.buttons.stop.label")),1)])])):V("",!0)]),a.apiKeyConfigured?V("",!0):(d(),h("div",Je,k(e(c)("settings.pages.providers.provider.elevenlabs.playground.validation.error-missing-api-key")),1)),g.value?V("",!0):(d(),h("div",Qe,k(e(c)("settings.pages.modules.speech.sections.section.playground.select-voice.required")),1)),f.value?(d(),h("div",We,k(f.value),1)):V("",!0),s.value?(d(),h("audio",{key:5,ref_key:"audioPlayer",ref:l,src:s.value,controls:"",class:"mt-2 w-full"},null,8,Xe)):V("",!0)]),U(S.$slots,"default")]))}}),Ye={flex:"~ col md:row gap-6"},Ze={flex:"~ col gap-6"},et={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},tt={flex:"~ col gap-4"},lt={flex:"~ col gap-6",class:"w-full md:w-[60%]"},st={"w-full":"","rounded-xl":""},mt=N({__name:"SpeechProviderSettings",props:{providerId:null,defaultModel:null,additionalSettings:null},setup(a){const i=a,{t:b}=E(),c=re(),y=fe(),w=ce(),{providers:s}=ne(y),f=R(()=>y.getProviderMetadata(i.providerId)),l=R({get:()=>{var o;return((o=s.value[i.providerId])==null?void 0:o.apiKey)||""},set:o=>{s.value[i.providerId]||(s.value[i.providerId]={}),s.value[i.providerId].apiKey=o}}),v=R({get:()=>{var o,u,_;return((o=s.value[i.providerId])==null?void 0:o.baseUrl)||((_=(u=f.value)==null?void 0:u.defaultOptions)==null?void 0:_.baseUrl)||""},set:o=>{s.value[i.providerId]||(s.value[i.providerId]={}),s.value[i.providerId].baseUrl=o}}),r=x("Hello! This is a test of voice synthesis."),n=x(!1),g=x(""),P=x(""),$=x(null),S=x(!1),p=x(""),m=x(""),B=x({});function te(){var o;(o=s.value[i.providerId])!=null&&o.voiceSettings?B.value={...s.value[i.providerId].voiceSettings}:B.value={pitch:0,speed:1,volume:0,...i.additionalSettings}}de(()=>{var o,u,_,L;y.initializeProvider(i.providerId),l.value=((o=s.value[i.providerId])==null?void 0:o.apiKey)||"",v.value=((u=s.value[i.providerId])==null?void 0:u.baseUrl)||((L=(_=f.value)==null?void 0:_.defaultOptions)==null?void 0:L.baseUrl)||"",te(),y.configuredProviders[i.providerId]&&w.loadVoicesForProvider(i.providerId)});const F=ue(()=>{var o,u;s.value[i.providerId]={...s.value[i.providerId],apiKey:l.value,baseUrl:v.value||((u=(o=f.value)==null?void 0:o.defaultOptions)==null?void 0:u.baseUrl)||"",voiceSettings:{...B.value}}},1e3);j([l,v],F),j(B,F,{deep:!0});async function le(){if(!r.value.trim()&&!S.value||S.value&&!p.value.trim())return;const o=y.getProviderInstance(i.providerId);if(!o){console.error("Failed to initialize speech provider");return}if(!m.value){console.error("No active speech voice selected");return}n.value=!0,P.value="";try{g.value&&D();const u=i.defaultModel||"default",_=S.value?p.value:r.value,L=await me({...o.speech(u,{voiceSettings:B.value}),input:_,voice:m.value});g.value=URL.createObjectURL(new Blob([L])),setTimeout(()=>{$.value&&$.value.play()},100)}catch(u){console.error("Error generating speech:",u),P.value=u instanceof Error?u.message:"An unknown error occurred"}finally{n.value=!1}}function D(){$.value&&($.value.pause(),$.value.currentTime=0),g.value&&(URL.revokeObjectURL(g.value),g.value="")}Z(()=>{g.value&&URL.revokeObjectURL(g.value)});function se(){var o,u;B.value={...((u=(o=f.value)==null?void 0:o.defaultOptions)==null?void 0:u.voiceSettings)||{}},F()}function oe(o,u){B.value[o]=u}const A=R(()=>({voiceSettings:B.value,updateVoiceSettings:oe,isGenerating:n.value,testText:r.value,useSSML:S.value,ssmlText:p.value,generateTestSpeech:le,stopTestAudio:D,audioUrl:g.value,audioPlayer:$.value,errorMessage:P.value}));return(o,u)=>{var _,L;return d(),I(Be,{"provider-name":(_=f.value)==null?void 0:_.localizedName,"provider-icon":(L=f.value)==null?void 0:L.icon,"on-back":()=>e(c).back()},{default:K(()=>[t("div",Ye,[M(e(xe),{class:"w-full md:w-[40%]"},{default:K(()=>[M(e(he),{title:e(b)("settings.pages.providers.common.section.basic.title"),description:e(b)("settings.pages.providers.common.section.basic.description"),"on-reset":se},{default:K(()=>{var O;return[M(e(ye),{modelValue:l.value,"onUpdate:modelValue":u[0]||(u[0]=z=>l.value=z),"provider-name":(O=f.value)==null?void 0:O.localizedName,placeholder:"sk-"},null,8,["modelValue","provider-name"]),U(o.$slots,"basic-settings")]}),_:3},8,["title","description"]),t("div",Ze,[t("h2",et,k(e(b)("settings.pages.providers.common.section.voice.title")),1),t("div",tt,[U(o.$slots,"voice-settings",W(X(A.value)))])]),M(e(ge),{title:e(b)("settings.pages.providers.common.section.advanced.title")},{default:K(()=>{var O,z;return[M(e(be),{modelValue:v.value,"onUpdate:modelValue":u[1]||(u[1]=ae=>v.value=ae),placeholder:((z=(O=f.value)==null?void 0:O.defaultOptions)==null?void 0:z.baseUrl)||"",required:""},null,8,["modelValue","placeholder"]),U(o.$slots,"advanced-settings")]}),_:3},8,["title"])]),_:3}),t("div",lt,[t("div",st,[U(o.$slots,"playground",W(X(A.value)))])])])]),_:3},8,["provider-name","provider-icon","on-back"])}}}),ot={flex:"~ col gap-4"},ft=N({__name:"SpeechVoiceSettings",props:ve({settings:null,showPitch:{type:Boolean},showSpeed:{type:Boolean},showStyle:{type:Boolean},showStability:{type:Boolean},showSimilarityBoost:{type:Boolean},showVolume:{type:Boolean},showSpeakerBoost:{type:Boolean}},{pitch:{required:!1,default:0},pitchModifiers:{},speed:{required:!1,default:1},speedModifiers:{},volume:{required:!1,default:0},volumeModifiers:{},style:{required:!1,default:0},styleModifiers:{},stability:{required:!1,default:.5},stabilityModifiers:{},similarityBoost:{required:!1,default:.75},similarityBoostModifiers:{},useSpeakerBoost:{type:Boolean,required:!1,default:!1},useSpeakerBoostModifiers:{}}),emits:["update:pitch","update:speed","update:volume","update:style","update:stability","update:similarityBoost","update:useSpeakerBoost"],setup(a){const i=T(a,"pitch"),b=T(a,"speed"),c=T(a,"volume"),y=T(a,"style"),w=T(a,"stability"),s=T(a,"similarityBoost"),f=T(a,"useSpeakerBoost"),{t:l}=E();return(v,r)=>(d(),h("div",ot,[a.showPitch?(d(),I(e(C),{key:0,modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=n=>i.value=n),label:e(l)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:e(l)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":n=>`${n}%`},null,8,["modelValue","label","description","format-value"])):V("",!0),a.showSpeed?(d(),I(e(C),{key:1,modelValue:b.value,"onUpdate:modelValue":r[1]||(r[1]=n=>b.value=n),label:e(l)("settings.pages.providers.provider.common.fields.field.speed.label"),description:e(l)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showVolume?(d(),I(e(C),{key:2,modelValue:c.value,"onUpdate:modelValue":r[2]||(r[2]=n=>c.value=n),label:e(l)("settings.pages.providers.provider.common.fields.field.volume.label"),description:e(l)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":n=>`${n}%`},null,8,["modelValue","label","description","format-value"])):V("",!0),a.showStyle?(d(),I(e(C),{key:3,modelValue:y.value,"onUpdate:modelValue":r[3]||(r[3]=n=>y.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.style.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.style.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showStability?(d(),I(e(C),{key:4,modelValue:w.value,"onUpdate:modelValue":r[4]||(r[4]=n=>w.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.stability.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.stability.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showSimilarityBoost?(d(),I(e(C),{key:5,modelValue:s.value,"onUpdate:modelValue":r[5]||(r[5]=n=>s.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"])):V("",!0),a.showSpeakerBoost?(d(),I(e(ee),{key:6,modelValue:f.value,"onUpdate:modelValue":r[6]||(r[6]=n=>f.value=n),label:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.label"),description:e(l)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.description")},null,8,["modelValue","label","description"])):V("",!0),U(v.$slots,"default")]))}});export{ct as _,ft as a,mt as b}; diff --git a/assets/TestDummyMarker-D7SLWeDD.css b/assets/TestDummyMarker-D7SLWeDD.css new file mode 100644 index 0000000000000000000000000000000000000000..be526ed6a668b9c96b84b98364e9d3d21d662b2a --- /dev/null +++ b/assets/TestDummyMarker-D7SLWeDD.css @@ -0,0 +1 @@ +.form_input-range[data-v-5db364fb]{--height: 2em;min-height:var(--height);-webkit-appearance:none;-moz-appearance:none;appearance:none;background:transparent;border-radius:4px;transition:background-color .2s ease;--thumb-width: 4px;--thumb-height: var(--height);--thumb-box-shadow: 0 0 0px #e6e6e6;--thumb-border: none;--thumb-border-radius: 999px;--thumb-background: oklch(80% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-hover: oklch(90% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-active: oklch(70% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--track-height: calc(var(--height) - var(--track-value-padding) * 2);--track-box-shadow: none;--track-border: solid 2px rgb(238, 238, 238);--track-border-radius: 6px;--track-background: rgb(238, 238, 238);--track-background-hover: rgb(238, 238, 238);--track-background-active: rgb(238, 238, 238);--track-value-background: rgb(255, 255, 255);--track-value-background-hover: rgb(255, 255, 255);--track-value-background-active: rgb(255, 255, 255);--track-value-padding: 2px}.dark .form_input-range[data-v-5db364fb]{--thumb-background: oklch(70% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-hover: oklch(90% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-active: oklch(80% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--track-border: solid 2px rgb(44, 44, 44);--track-background: rgb(44, 44, 44);--track-background-hover: rgb(44, 44, 44);--track-background-active: rgb(44, 44, 44);--track-value-background: rgb(164, 164, 164);--track-value-background-hover: rgb(164, 164, 164);--track-value-background-active: rgb(164, 164, 164)}.form_input-range.slider-progress[data-v-5db364fb]{--range: calc(var(--max) - var(--min));--ratio: calc((var(--value) - var(--min)) / var(--range));--sx: calc(.5 * 0em + var(--ratio) * (100% - 0em))}.form_input-range[data-v-5db364fb]:focus{outline:none}.form_input-range[data-v-5db364fb]::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:var(--thumb-width);height:var(--thumb-height);border-radius:var(--thumb-border-radius);background:var(--thumb-background);border:var(--thumb-border);box-shadow:var(--thumb-box-shadow);margin-top:calc(var(--track-height) * .5 - var(--thumb-height) * .5 - 2px);margin-left:calc(0 - var(--track-value-padding));cursor:col-resize;transition:background .2s ease-in-out,box-shadow .2s ease-in-out,border-color .2s ease-in-out,transform .2s ease-in-out}.form_input-range[data-v-5db364fb]::-webkit-slider-runnable-track{height:var(--track-height);border:var(--track-border);border-radius:var(--track-border-radius);background:var(--track-background);box-shadow:var(--track-box-shadow);position:relative;cursor:col-resize;transition:box-shadow .2s ease-in-out,border-color .2s ease-in-out}.form_input-range[data-v-5db364fb]::-webkit-slider-thumb:hover{background:var(--thumb-background-hover)}.form_input-range[data-v-5db364fb]:hover::-webkit-slider-runnable-track{background:var(--track-background-hover)}.form_input-range[data-v-5db364fb]::-webkit-slider-thumb:active{background:var(--thumb-background-active)}.form_input-range[data-v-5db364fb]:active::-webkit-slider-runnable-track{background:var(--track-background-active)}.form_input-range.slider-progress[data-v-5db364fb]::-webkit-slider-runnable-track{margin-right:calc(0 - var(--track-value-padding));background:linear-gradient(var(--track-value-background),var(--track-value-background)) 0 / var(--sx) 100% no-repeat,var(--track-background)}.form_input-range.slider-progress[data-v-5db364fb]:hover::-webkit-slider-runnable-track{background:linear-gradient(var(--track-value-background-hover),var(--track-value-background-hover)) 0 / var(--sx) 100% no-repeat,var(--track-background-hover)}.form_input-range.slider-progress[data-v-5db364fb]:active::-webkit-slider-runnable-track{background:linear-gradient(var(--track-value-background-active),var(--track-value-background-active)) 0 / var(--sx) 100% no-repeat,var(--track-background-active)}.form_input-range[data-v-5db364fb]::-moz-range-thumb{width:var(--thumb-width);height:var(--thumb-height);border-radius:var(--thumb-border-radius);background:var(--thumb-background);border:none;box-shadow:var(--thumb-box-shadow);cursor:col-resize;margin-left:calc(0 - var(--track-value-padding))}.form_input-range[data-v-5db364fb]::-moz-range-track{height:var(--track-height);border:var(--track-border);border-radius:var(--track-border-radius);background:var(--track-background);box-shadow:var(--track-box-shadow);cursor:col-resize;width:calc(100% - var(--track-value-padding) * 2)}.form_input-range[data-v-5db364fb]::-moz-range-thumb:hover{background:var(--thumb-background-hover)}.form_input-range[data-v-5db364fb]:hover::-moz-range-track{background:var(--track-background-hover)}.form_input-range[data-v-5db364fb]::-moz-range-thumb:active{background:var(--thumb-background-active)}.form_input-range[data-v-5db364fb]:active::-moz-range-track{background:var(--track-background-active)}.form_input-range.slider-progress[data-v-5db364fb]::-moz-range-track{background:linear-gradient(var(--track-value-background),var(--track-value-background)) 0 / var(--sx) 100% no-repeat,var(--track-background)}.form_input-range.slider-progress[data-v-5db364fb]:hover::-moz-range-track{background:linear-gradient(var(--track-value-background-hover),var(--track-value-background-hover)) 0 / var(--sx) 100% no-repeat,var(--track-background-hover)}.form_input-range.slider-progress[data-v-5db364fb]:active::-moz-range-track{background:linear-gradient(var(--track-value-background-active),var(--track-value-background-active)) 0 / var(--sx) 100% no-repeat,var(--track-background-active)}.form_input-range[data-v-5db364fb]::-ms-fill-upper{background:transparent;border-color:transparent}.form_input-range[data-v-5db364fb]::-ms-fill-lower{background:transparent;border-color:transparent}.form_input-range[data-v-5db364fb]::-ms-thumb{width:var(--thumb-width);height:var(--thumb-height);border-radius:var(--thumb-border-radius);background:var(--thumb-background);border:var(--thumb-border);box-shadow:var(--thumb-box-shadow);margin-top:0;margin-left:calc(0 - var(--track-value-padding));box-sizing:border-box;cursor:col-resize}.form_input-range[data-v-5db364fb]::-ms-track{height:var(--track-height);border-radius:var(--track-border-radius);background:var(--track-background);border:var(--track-border);box-shadow:var(--track-box-shadow);box-sizing:border-box;cursor:col-resize}.form_input-range[data-v-5db364fb]::-ms-thumb:hover{background:var(--thumb-background-hover)}.form_input-range[data-v-5db364fb]:hover::-ms-track{background:var(--track-background-hover)}.form_input-range[data-v-5db364fb]::-ms-thumb:active{background:var(--thumb-background-active)}.form_input-range[data-v-5db364fb]:active::-ms-track{background:var(--track-background-active)}.form_input-range.slider-progress[data-v-5db364fb]::-ms-fill-lower{height:var(--track-height);border-radius:var(--track-border-radius) 0 0 var(--track-border-radius);margin:0;background:var(--track-value-background);border:none;border-right-width:0;margin-left:calc(var(--track-value-padding));margin-right:calc(0 - var(--track-value-padding))}.form_input-range.slider-progress[data-v-5db364fb]:hover::-ms-fill-lower{background:var(--track-value-background-hover)}.form_input-range.slider-progress[data-v-5db364fb]:active::-ms-fill-lower{background:var(--track-value-background-active)}.volumed[data-v-568551bc]{transform-style:preserve-3d;width:fit-content;height:fit-content}.test-dummy-flat[data-v-b4ef37ac]{display:inline-block;position:relative}.test-dummy-flat .marker[data-v-b4ef37ac]{position:absolute;top:0;right:0;bottom:0;left:0;background:conic-gradient(#ffeb3b,#ffeb3b 90deg,#000 90deg,#000 180deg,#ffeb3b 180deg,#ffeb3b 270deg,#000 270deg,#000 360deg);border-radius:50%;box-shadow:0 4px 12px #b9b9b933}.dark .test-dummy-flat .marker[data-v-b4ef37ac]{box-shadow:0 4px 12px #0003} diff --git a/assets/TestDummyMarker-vebZ6Nf0.css b/assets/TestDummyMarker-vebZ6Nf0.css deleted file mode 100644 index 97e2b7f47b16810ffc88c323937bf36537adb8e3..0000000000000000000000000000000000000000 --- a/assets/TestDummyMarker-vebZ6Nf0.css +++ /dev/null @@ -1 +0,0 @@ -.data-gui-range[data-v-8d439080]{--height: 2em;min-height:var(--height);-webkit-appearance:none;-moz-appearance:none;appearance:none;background:transparent;border-radius:4px;transition:background-color .2s ease;--thumb-width: 4px;--thumb-height: var(--height);--thumb-box-shadow: 0 0 0px #e6e6e6;--thumb-border: none;--thumb-border-radius: 999px;--thumb-background: oklch(80% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-hover: oklch(90% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-active: oklch(70% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--track-height: calc(var(--height) - var(--track-value-padding) * 2);--track-box-shadow: none;--track-border: solid 2px rgb(238, 238, 238);--track-border-radius: 6px;--track-background: rgb(238, 238, 238);--track-background-hover: rgb(238, 238, 238);--track-background-active: rgb(238, 238, 238);--track-value-background: rgb(255, 255, 255);--track-value-background-hover: rgb(255, 255, 255);--track-value-background-active: rgb(255, 255, 255);--track-value-padding: 2px}.dark .data-gui-range[data-v-8d439080]{--thumb-background: oklch(70% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-hover: oklch(90% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--thumb-background-active: oklch(80% var(--theme-colors-chroma-200) calc(var(--theme-colors-hue) + 0));--track-border: solid 2px rgb(44, 44, 44);--track-background: rgb(44, 44, 44);--track-background-hover: rgb(44, 44, 44);--track-background-active: rgb(44, 44, 44);--track-value-background: rgb(164, 164, 164);--track-value-background-hover: rgb(164, 164, 164);--track-value-background-active: rgb(164, 164, 164)}.data-gui-range.slider-progress[data-v-8d439080]{--range: calc(var(--max) - var(--min));--ratio: calc((var(--value) - var(--min)) / var(--range));--sx: calc(.5 * 0em + var(--ratio) * (100% - 0em))}.data-gui-range[data-v-8d439080]:focus{outline:none}.data-gui-range[data-v-8d439080]::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:var(--thumb-width);height:var(--thumb-height);border-radius:var(--thumb-border-radius);background:var(--thumb-background);border:var(--thumb-border);box-shadow:var(--thumb-box-shadow);margin-top:calc(var(--track-height) * .5 - var(--thumb-height) * .5 - 2px);margin-left:calc(0 - var(--track-value-padding));cursor:col-resize;transition:background .2s ease-in-out,box-shadow .2s ease-in-out,border-color .2s ease-in-out,transform .2s ease-in-out}.data-gui-range[data-v-8d439080]::-webkit-slider-runnable-track{height:var(--track-height);border:var(--track-border);border-radius:var(--track-border-radius);background:var(--track-background);box-shadow:var(--track-box-shadow);position:relative;cursor:col-resize;transition:box-shadow .2s ease-in-out,border-color .2s ease-in-out}.data-gui-range[data-v-8d439080]::-webkit-slider-thumb:hover{background:var(--thumb-background-hover)}.data-gui-range[data-v-8d439080]:hover::-webkit-slider-runnable-track{background:var(--track-background-hover)}.data-gui-range[data-v-8d439080]::-webkit-slider-thumb:active{background:var(--thumb-background-active)}.data-gui-range[data-v-8d439080]:active::-webkit-slider-runnable-track{background:var(--track-background-active)}.data-gui-range.slider-progress[data-v-8d439080]::-webkit-slider-runnable-track{margin-right:calc(0 - var(--track-value-padding));background:linear-gradient(var(--track-value-background),var(--track-value-background)) 0 / var(--sx) 100% no-repeat,var(--track-background)}.data-gui-range.slider-progress[data-v-8d439080]:hover::-webkit-slider-runnable-track{background:linear-gradient(var(--track-value-background-hover),var(--track-value-background-hover)) 0 / var(--sx) 100% no-repeat,var(--track-background-hover)}.data-gui-range.slider-progress[data-v-8d439080]:active::-webkit-slider-runnable-track{background:linear-gradient(var(--track-value-background-active),var(--track-value-background-active)) 0 / var(--sx) 100% no-repeat,var(--track-background-active)}.data-gui-range[data-v-8d439080]::-moz-range-thumb{width:var(--thumb-width);height:var(--thumb-height);border-radius:var(--thumb-border-radius);background:var(--thumb-background);border:none;box-shadow:var(--thumb-box-shadow);cursor:col-resize;margin-left:calc(0 - var(--track-value-padding))}.data-gui-range[data-v-8d439080]::-moz-range-track{height:var(--track-height);border:var(--track-border);border-radius:var(--track-border-radius);background:var(--track-background);box-shadow:var(--track-box-shadow);cursor:col-resize;width:calc(100% - var(--track-value-padding) * 2)}.data-gui-range[data-v-8d439080]::-moz-range-thumb:hover{background:var(--thumb-background-hover)}.data-gui-range[data-v-8d439080]:hover::-moz-range-track{background:var(--track-background-hover)}.data-gui-range[data-v-8d439080]::-moz-range-thumb:active{background:var(--thumb-background-active)}.data-gui-range[data-v-8d439080]:active::-moz-range-track{background:var(--track-background-active)}.data-gui-range.slider-progress[data-v-8d439080]::-moz-range-track{background:linear-gradient(var(--track-value-background),var(--track-value-background)) 0 / var(--sx) 100% no-repeat,var(--track-background)}.data-gui-range.slider-progress[data-v-8d439080]:hover::-moz-range-track{background:linear-gradient(var(--track-value-background-hover),var(--track-value-background-hover)) 0 / var(--sx) 100% no-repeat,var(--track-background-hover)}.data-gui-range.slider-progress[data-v-8d439080]:active::-moz-range-track{background:linear-gradient(var(--track-value-background-active),var(--track-value-background-active)) 0 / var(--sx) 100% no-repeat,var(--track-background-active)}.data-gui-range[data-v-8d439080]::-ms-fill-upper{background:transparent;border-color:transparent}.data-gui-range[data-v-8d439080]::-ms-fill-lower{background:transparent;border-color:transparent}.data-gui-range[data-v-8d439080]::-ms-thumb{width:var(--thumb-width);height:var(--thumb-height);border-radius:var(--thumb-border-radius);background:var(--thumb-background);border:var(--thumb-border);box-shadow:var(--thumb-box-shadow);margin-top:0;margin-left:calc(0 - var(--track-value-padding));box-sizing:border-box;cursor:col-resize}.data-gui-range[data-v-8d439080]::-ms-track{height:var(--track-height);border-radius:var(--track-border-radius);background:var(--track-background);border:var(--track-border);box-shadow:var(--track-box-shadow);box-sizing:border-box;cursor:col-resize}.data-gui-range[data-v-8d439080]::-ms-thumb:hover{background:var(--thumb-background-hover)}.data-gui-range[data-v-8d439080]:hover::-ms-track{background:var(--track-background-hover)}.data-gui-range[data-v-8d439080]::-ms-thumb:active{background:var(--thumb-background-active)}.data-gui-range[data-v-8d439080]:active::-ms-track{background:var(--track-background-active)}.data-gui-range.slider-progress[data-v-8d439080]::-ms-fill-lower{height:var(--track-height);border-radius:var(--track-border-radius) 0 0 var(--track-border-radius);margin:0;background:var(--track-value-background);border:none;border-right-width:0;margin-left:calc(var(--track-value-padding));margin-right:calc(0 - var(--track-value-padding))}.data-gui-range.slider-progress[data-v-8d439080]:hover::-ms-fill-lower{background:var(--track-value-background-hover)}.data-gui-range.slider-progress[data-v-8d439080]:active::-ms-fill-lower{background:var(--track-value-background-active)}.volumed[data-v-568551bc]{transform-style:preserve-3d;width:fit-content;height:fit-content}.test-dummy-flat[data-v-b4ef37ac]{display:inline-block;position:relative}.test-dummy-flat .marker[data-v-b4ef37ac]{position:absolute;top:0;right:0;bottom:0;left:0;background:conic-gradient(#ffeb3b,#ffeb3b 90deg,#000 90deg,#000 180deg,#ffeb3b 180deg,#ffeb3b 270deg,#000 270deg,#000 360deg);border-radius:50%;box-shadow:0 4px 12px #b9b9b933}.dark .test-dummy-flat .marker[data-v-b4ef37ac]{box-shadow:0 4px 12px #0003} diff --git a/assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js b/assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js similarity index 68% rename from assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js rename to assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js index 772f4d03ad83b209b86193bda55c06723e91d2ce..26e46637fcb4d661ce60ed1d909698a46d2f6df1 100644 --- a/assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js +++ b/assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js @@ -1 +1 @@ -import{bx as P,d as c,b$ as I,bQ as k,c1 as N,bZ as C,x as y,o as m,y as _,p as w,e as i,bW as D,c9 as L,g as x,h as b,cd as S,bV as z,ce as U,w as A,c as g,by as G,E as H,cf as K,C as W,cg as X,c0 as Y,bG as M,b as $,bF as q,a as h,D as V,m as O,A as J,bJ as Q,bn as B,n as j,br as E,H as Z}from"./index-rD0Uu1v9.js";function R(t){return t?t.flatMap(e=>e.type===P?R(e.children):[e]):[]}const ee=c({name:"PrimitiveSlot",inheritAttrs:!1,setup(t,{attrs:e,slots:a}){return()=>{var p,v;if(!a.default)return null;const n=R(a.default()),l=n.findIndex(d=>d.type!==I);if(l===-1)return n;const o=n[l];(p=o.props)==null||delete p.ref;const r=o.props?k(e,o.props):e;e.class&&((v=o.props)!=null&&v.class)&&delete o.props.class;const s=N(o,r);for(const d in r)d.startsWith("on")&&(s.props||(s.props={}),s.props[d]=r[d]);return n.length===1?s:(n[l]=s,n)}}}),F=c({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(t,{attrs:e,slots:a}){const n=t.asChild?"template":t.as;return typeof n=="string"&&["area","img","input"].includes(n)?()=>C(n,e):n!=="template"?()=>C(t.as,e,{default:a.default}):()=>C(ee,e,{default:a.default})}}),te=c({__name:"VisuallyHidden",props:{feature:{default:"focusable"},asChild:{type:Boolean},as:{default:"span"}},setup(t){return(e,a)=>(m(),y(i(F),{as:e.as,"as-child":e.asChild,"aria-hidden":e.feature==="focusable"?"true":void 0,"data-hidden":e.feature==="fully-hidden"?"":void 0,tabindex:e.feature==="fully-hidden"?"-1":void 0,style:{position:"absolute",border:0,width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",wordWrap:"normal"}},{default:_(()=>[w(e.$slots,"default")]),_:3},8,["as","as-child","aria-hidden","data-hidden","tabindex"]))}});function ae(t,e){const a=`${t}Context`,n=Symbol(a);return[r=>{const s=D(n,r);if(s||s===null)return s;throw new Error(`Injection \`${n.toString()}\` not found. Component must be used within ${Array.isArray(t)?`one of the following components: ${t.join(", ")}`:`\`${t}\``}`)},r=>(L(n,r),r)]}function T(){const t=z(),e=x(),a=b(()=>{var r,s;return["#text","#comment"].includes((r=e.value)==null?void 0:r.$el.nodeName)?(s=e.value)==null?void 0:s.$el.nextElementSibling:S(e)}),n=Object.assign({},t.exposed),l={};for(const r in t.props)Object.defineProperty(l,r,{enumerable:!0,configurable:!0,get:()=>t.props[r]});if(Object.keys(n).length>0)for(const r in n)Object.defineProperty(l,r,{enumerable:!0,configurable:!0,get:()=>n[r]});Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>t.vnode.el}),t.exposed=l;function o(r){e.value=r,r&&(Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>r instanceof Element?r:r.$el}),t.exposed=l)}return{forwardRef:o,currentRef:e,currentElement:a}}function ne(){const t=x(),e=b(()=>{var a,n;return["#text","#comment"].includes((a=t.value)==null?void 0:a.$el.nodeName)?(n=t.value)==null?void 0:n.$el.nextElementSibling:S(t)});return{primitiveElement:t,currentElement:e}}function le(t){return b(()=>{var e;return U(t)?!!((e=S(t))!=null&&e.closest("form")):!0})}const oe=c({inheritAttrs:!1,__name:"VisuallyHiddenInputBubble",props:{name:{},value:{},checked:{type:Boolean,default:void 0},required:{type:Boolean},disabled:{type:Boolean},feature:{default:"fully-hidden"}},setup(t){const e=t,{primitiveElement:a,currentElement:n}=ne(),l=b(()=>e.checked??e.value);return A(l,(o,r)=>{if(!n.value)return;const s=n.value,p=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(p,"value").set;if(d&&o!==r){const u=new Event("input",{bubbles:!0}),f=new Event("change",{bubbles:!0});d.call(s,o),s.dispatchEvent(u),s.dispatchEvent(f)}}),(o,r)=>(m(),y(te,k({ref_key:"primitiveElement",ref:a},{...e,...o.$attrs},{as:"input"}),null,16))}}),re=c({inheritAttrs:!1,__name:"VisuallyHiddenInput",props:{name:{},value:{},checked:{type:Boolean,default:void 0},required:{type:Boolean},disabled:{type:Boolean},feature:{default:"fully-hidden"}},setup(t){const e=t,a=b(()=>typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?[{name:e.name,value:e.value}]:typeof e.value=="object"&&Array.isArray(e.value)?e.value.flatMap((n,l)=>typeof n=="object"?Object.entries(n).map(([o,r])=>({name:`[${e.name}][${l}][${o}]`,value:r})):{name:`[${e.name}][${l}]`,value:n}):e.value!==null&&typeof e.value=="object"&&!Array.isArray(e.value)?Object.entries(e.value).map(([n,l])=>({name:`[${e.name}][${n}]`,value:l})):[]);return(n,l)=>(m(!0),g(P,null,G(a.value,o=>(m(),y(oe,k({key:o.name,ref_for:!0},{...e,...n.$attrs},{name:o.name,value:o.value}),null,16,["name","value"]))),128))}}),[se,ue]=ae("SwitchRoot"),ie=c({__name:"SwitchRoot",props:{defaultValue:{type:Boolean},modelValue:{type:[Boolean,null],default:void 0},disabled:{type:Boolean},id:{},value:{default:"on"},asChild:{type:Boolean},as:{default:"button"},name:{},required:{type:Boolean}},emits:["update:modelValue"],setup(t,{emit:e}){const a=t,n=e,{disabled:l}=H(a),o=K(a,"modelValue",n,{defaultValue:a.defaultValue,passive:a.modelValue===void 0});function r(){l.value||(o.value=!o.value)}const{forwardRef:s,currentElement:p}=T(),v=le(p),d=b(()=>{var u;return a.id&&p.value?(u=document.querySelector(`[for="${a.id}"]`))==null?void 0:u.innerText:void 0});return ue({modelValue:o,toggleCheck:r,disabled:l}),(u,f)=>(m(),y(i(F),k(u.$attrs,{id:u.id,ref:i(s),role:"switch",type:u.as==="button"?"button":void 0,value:u.value,"aria-label":u.$attrs["aria-label"]||d.value,"aria-checked":i(o),"aria-required":u.required,"data-state":i(o)?"checked":"unchecked","data-disabled":i(l)?"":void 0,"as-child":u.asChild,as:u.as,disabled:i(l),onClick:r,onKeydown:X(Y(r,["prevent"]),["enter"])}),{default:_(()=>[w(u.$slots,"default",{modelValue:i(o)}),i(v)&&u.name?(m(),y(i(re),{key:0,type:"checkbox",name:u.name,disabled:i(l),required:u.required,value:u.value,checked:!!i(o)},null,8,["name","disabled","required","value","checked"])):W("",!0)]),_:3},16,["id","type","value","aria-label","aria-checked","aria-required","data-state","data-disabled","as-child","as","disabled","onKeydown"]))}}),de=c({__name:"SwitchThumb",props:{asChild:{type:Boolean},as:{default:"span"}},setup(t){const e=se();return T(),(a,n)=>{var l;return m(),y(i(F),{"data-state":(l=i(e).modelValue)!=null&&l.value?"checked":"unchecked","data-disabled":i(e).disabled.value?"":void 0,"as-child":a.asChild,as:a.as},{default:_(()=>[w(a.$slots,"default")]),_:3},8,["data-state","data-disabled","as-child","as"])}}}),ce=c({__name:"Checkbox",props:{modelValue:{type:Boolean,required:!0},modelModifiers:{}},emits:["update:modelValue"],setup(t){const e=M(t,"modelValue");return(a,n)=>(m(),y(i(ie),{modelValue:e.value,"onUpdate:modelValue":n[0]||(n[0]=l=>e.value=l),transition:"background duration-250 ease-in-out",outline:"focus-within:none",flex:"~",border:"neutral-300 dark:neutral-700 data-[state=checked]:primary-200 data-[state=unchecked]:neutral-300 focus-within:neutral-800",bg:"data-[state=checked]:primary-400 data-[state=unchecked]:neutral-300 data-[state=checked]:dark:primary-400/80 dark:data-[state=unchecked]:neutral-800",relative:"","h-7":"",w:"12.5","rounded-full":"",shadow:"sm focus-within:shadow-neutral-800 focus-within:[0_0_0_1px] "},{default:_(()=>[$(i(de),{"my-auto":"","size-6":"",flex:"","items-center":"","justify-center":"","translate-x":"0.5 data-[state=checked]:full","rounded-full":"","bg-white":"","text-xs":"","shadow-xl":"",transition:"transform duration-250 ease-in-out","will-change-transform":""})]),_:1},8,["modelValue"]))}}),me={flex:"~ col gap-4"},pe={flex:"~ row","items-center":"","gap-2":""},fe={flex:"1"},ve={class:"flex items-center gap-1 text-sm font-medium"},he={class:"text-xs text-neutral-500 dark:text-neutral-400"},Pe=c({__name:"FieldCheckbox",props:q({label:null,description:null},{modelValue:{type:Boolean,required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,a=M(t,"modelValue");return(n,l)=>(m(),g("label",me,[h("div",pe,[h("div",fe,[h("div",ve,V(e.label),1),h("div",he,V(e.description),1)]),$(ce,{modelValue:a.value,"onUpdate:modelValue":l[0]||(l[0]=o=>a.value=o)},null,8,["modelValue"])])]))}}),be=["min","max","step"],ye=c({__name:"Range",props:{modelValue:null,min:{default:0},max:{default:100},step:{default:1},disabled:{type:Boolean,default:!1},thumbColor:{default:"#9090906e"},trackColor:{default:"gray"},trackValueColor:{default:"red"}},emits:["update:modelValue"],setup(t,{emit:e}){const a=t,n=e,l=b(()=>a.min*1e4),o=b(()=>a.max*1e4),r=b(()=>a.step*1e4),s=x(),p=x(a.modelValue*1e4);A(p,d=>{n("update:modelValue",d/1e4),v()}),O(()=>{v()});function v(){s.value&&(s.value.style.setProperty("--value",s.value.value),s.value.style.setProperty("--min",s.value.min?s.value.min:a.min.toString()),s.value.style.setProperty("--max",s.value.max?s.value.max:a.max.toString()))}return(d,u)=>J((m(),g("input",{ref_key:"sliderRef",ref:s,"onUpdate:modelValue":u[0]||(u[0]=f=>p.value=f),type:"range",min:l.value,max:o.value,step:r.value,class:"data-gui-range slider-progress",onInput:u[1]||(u[1]=f=>{f.target.style.setProperty("--value",f.target.value)})},null,40,be)),[[Q,p.value,void 0,{number:!0}]])}}),_e=B(ye,[["__scopeId","data-v-8d439080"]]),xe={flex:"~ col gap-4"},ge={flex:"~ row","items-center":"","gap-2":""},Ve={flex:"1"},$e={class:"flex items-center gap-1 text-sm font-medium"},we={class:"text-xs text-neutral-500 dark:text-neutral-400"},ke={"font-mono":""},Ce={flex:"~ row","items-center":"","gap-2":""},Ae=c({__name:"FieldRange",props:q({min:null,max:null,step:null,label:null,description:null,formatValue:{type:Function}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,a=M(t,"modelValue");return(n,l)=>{var o;return m(),g("label",xe,[h("div",ge,[h("div",Ve,[h("div",$e,V(t.label),1),h("div",we,V(t.description),1)]),h("span",ke,V(((o=e.formatValue)==null?void 0:o.call(e,a.value))||a.value),1)]),h("div",Ce,[$(_e,{modelValue:a.value,"onUpdate:modelValue":l[0]||(l[0]=r=>a.value=r),min:t.min||0,max:t.max||1,step:t.step||.01,"w-full":""},null,8,["modelValue","min","max","step"])])])}}}),Ee=c({__name:"Volumed",props:{perspective:null,transform:null},setup(t){return(e,a)=>(m(),g("div",{class:"volumed",style:j({perspective:`${t.perspective}px`,transform:t.transform})},[w(e.$slots,"default",{},void 0,!0)],4))}}),Se=B(Ee,[["__scopeId","data-v-568551bc"]]),Me=c({__name:"CursorMomentum",props:{baseSpeed:{default:.1},friction:{default:.95},momentumFactor:{default:.005}},setup(t,{expose:e}){const a=t,n=x(1),l=x(0);let o=0;const r=E(()=>a.friction),s=E(()=>a.baseSpeed),p=E(()=>a.momentumFactor);function v(u){o||(o=u);const f=u-o;o=u,n.value=s.value+(n.value-s.value)*r.value,l.value+=n.value*f,requestAnimationFrame(v)}function d(u){const f=Math.sqrt(u.movementX**2+u.movementY**2);n.value+=f*p.value}return O(()=>{window.addEventListener("mousemove",d),requestAnimationFrame(v)}),Z(()=>{window.removeEventListener("mousemove",d)}),e({momentum:n,currentValue:l}),(u,f)=>w(u.$slots,"default",{momentum:n.value,currentValue:l.value})}}),Be=c({__name:"TestDummyMarkerFlat",props:{size:null},setup(t){return(e,a)=>(m(),g("div",{class:"test-dummy-flat",style:j({width:`${t.size}px`,height:`${t.size}px`})},a[0]||(a[0]=[h("div",{class:"marker"},null,-1)]),4))}}),je=B(Be,[["__scopeId","data-v-b4ef37ac"]]),qe=c({__name:"TestDummyMarker",setup(t){return(e,a)=>(m(),y(Me,{"base-speed":.1,friction:.95,"momentum-factor":5e-4},{default:_(({currentValue:n})=>[$(Se,{perspective:800,transform:"rotateX(45deg) translateY(3px)"},{default:_(()=>[$(je,{size:24,style:j({transform:`rotate(${n}deg)`})},null,8,["style"])]),_:2},1024)]),_:1}))}});export{Ae as _,Pe as a,qe as b}; +import{bx as P,d as c,b$ as I,bQ as k,c1 as N,bZ as C,x as y,o as m,y as _,p as w,e as i,bW as D,c9 as L,g as x,h as b,cd as S,bV as z,ce as U,w as A,c as g,by as G,E as H,cf as K,C as W,cg as X,c0 as Y,bG as M,b as $,bF as q,a as h,D as V,m as O,A as J,bJ as Q,bn as B,n as j,br as E,H as Z}from"./index-Dlp4W1Zl.js";function R(t){return t?t.flatMap(e=>e.type===P?R(e.children):[e]):[]}const ee=c({name:"PrimitiveSlot",inheritAttrs:!1,setup(t,{attrs:e,slots:a}){return()=>{var f,v;if(!a.default)return null;const n=R(a.default()),l=n.findIndex(d=>d.type!==I);if(l===-1)return n;const o=n[l];(f=o.props)==null||delete f.ref;const r=o.props?k(e,o.props):e;e.class&&((v=o.props)!=null&&v.class)&&delete o.props.class;const s=N(o,r);for(const d in r)d.startsWith("on")&&(s.props||(s.props={}),s.props[d]=r[d]);return n.length===1?s:(n[l]=s,n)}}}),F=c({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(t,{attrs:e,slots:a}){const n=t.asChild?"template":t.as;return typeof n=="string"&&["area","img","input"].includes(n)?()=>C(n,e):n!=="template"?()=>C(t.as,e,{default:a.default}):()=>C(ee,e,{default:a.default})}}),te=c({__name:"VisuallyHidden",props:{feature:{default:"focusable"},asChild:{type:Boolean},as:{default:"span"}},setup(t){return(e,a)=>(m(),y(i(F),{as:e.as,"as-child":e.asChild,"aria-hidden":e.feature==="focusable"?"true":void 0,"data-hidden":e.feature==="fully-hidden"?"":void 0,tabindex:e.feature==="fully-hidden"?"-1":void 0,style:{position:"absolute",border:0,width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",wordWrap:"normal"}},{default:_(()=>[w(e.$slots,"default")]),_:3},8,["as","as-child","aria-hidden","data-hidden","tabindex"]))}});function ae(t,e){const a=`${t}Context`,n=Symbol(a);return[r=>{const s=D(n,r);if(s||s===null)return s;throw new Error(`Injection \`${n.toString()}\` not found. Component must be used within ${Array.isArray(t)?`one of the following components: ${t.join(", ")}`:`\`${t}\``}`)},r=>(L(n,r),r)]}function T(){const t=z(),e=x(),a=b(()=>{var r,s;return["#text","#comment"].includes((r=e.value)==null?void 0:r.$el.nodeName)?(s=e.value)==null?void 0:s.$el.nextElementSibling:S(e)}),n=Object.assign({},t.exposed),l={};for(const r in t.props)Object.defineProperty(l,r,{enumerable:!0,configurable:!0,get:()=>t.props[r]});if(Object.keys(n).length>0)for(const r in n)Object.defineProperty(l,r,{enumerable:!0,configurable:!0,get:()=>n[r]});Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>t.vnode.el}),t.exposed=l;function o(r){e.value=r,r&&(Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>r instanceof Element?r:r.$el}),t.exposed=l)}return{forwardRef:o,currentRef:e,currentElement:a}}function ne(){const t=x(),e=b(()=>{var a,n;return["#text","#comment"].includes((a=t.value)==null?void 0:a.$el.nodeName)?(n=t.value)==null?void 0:n.$el.nextElementSibling:S(t)});return{primitiveElement:t,currentElement:e}}function le(t){return b(()=>{var e;return U(t)?!!((e=S(t))!=null&&e.closest("form")):!0})}const oe=c({inheritAttrs:!1,__name:"VisuallyHiddenInputBubble",props:{name:{},value:{},checked:{type:Boolean,default:void 0},required:{type:Boolean},disabled:{type:Boolean},feature:{default:"fully-hidden"}},setup(t){const e=t,{primitiveElement:a,currentElement:n}=ne(),l=b(()=>e.checked??e.value);return A(l,(o,r)=>{if(!n.value)return;const s=n.value,f=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(f,"value").set;if(d&&o!==r){const u=new Event("input",{bubbles:!0}),p=new Event("change",{bubbles:!0});d.call(s,o),s.dispatchEvent(u),s.dispatchEvent(p)}}),(o,r)=>(m(),y(te,k({ref_key:"primitiveElement",ref:a},{...e,...o.$attrs},{as:"input"}),null,16))}}),re=c({inheritAttrs:!1,__name:"VisuallyHiddenInput",props:{name:{},value:{},checked:{type:Boolean,default:void 0},required:{type:Boolean},disabled:{type:Boolean},feature:{default:"fully-hidden"}},setup(t){const e=t,a=b(()=>typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?[{name:e.name,value:e.value}]:typeof e.value=="object"&&Array.isArray(e.value)?e.value.flatMap((n,l)=>typeof n=="object"?Object.entries(n).map(([o,r])=>({name:`[${e.name}][${l}][${o}]`,value:r})):{name:`[${e.name}][${l}]`,value:n}):e.value!==null&&typeof e.value=="object"&&!Array.isArray(e.value)?Object.entries(e.value).map(([n,l])=>({name:`[${e.name}][${n}]`,value:l})):[]);return(n,l)=>(m(!0),g(P,null,G(a.value,o=>(m(),y(oe,k({key:o.name,ref_for:!0},{...e,...n.$attrs},{name:o.name,value:o.value}),null,16,["name","value"]))),128))}}),[se,ue]=ae("SwitchRoot"),ie=c({__name:"SwitchRoot",props:{defaultValue:{type:Boolean},modelValue:{type:[Boolean,null],default:void 0},disabled:{type:Boolean},id:{},value:{default:"on"},asChild:{type:Boolean},as:{default:"button"},name:{},required:{type:Boolean}},emits:["update:modelValue"],setup(t,{emit:e}){const a=t,n=e,{disabled:l}=H(a),o=K(a,"modelValue",n,{defaultValue:a.defaultValue,passive:a.modelValue===void 0});function r(){l.value||(o.value=!o.value)}const{forwardRef:s,currentElement:f}=T(),v=le(f),d=b(()=>{var u;return a.id&&f.value?(u=document.querySelector(`[for="${a.id}"]`))==null?void 0:u.innerText:void 0});return ue({modelValue:o,toggleCheck:r,disabled:l}),(u,p)=>(m(),y(i(F),k(u.$attrs,{id:u.id,ref:i(s),role:"switch",type:u.as==="button"?"button":void 0,value:u.value,"aria-label":u.$attrs["aria-label"]||d.value,"aria-checked":i(o),"aria-required":u.required,"data-state":i(o)?"checked":"unchecked","data-disabled":i(l)?"":void 0,"as-child":u.asChild,as:u.as,disabled:i(l),onClick:r,onKeydown:X(Y(r,["prevent"]),["enter"])}),{default:_(()=>[w(u.$slots,"default",{modelValue:i(o)}),i(v)&&u.name?(m(),y(i(re),{key:0,type:"checkbox",name:u.name,disabled:i(l),required:u.required,value:u.value,checked:!!i(o)},null,8,["name","disabled","required","value","checked"])):W("",!0)]),_:3},16,["id","type","value","aria-label","aria-checked","aria-required","data-state","data-disabled","as-child","as","disabled","onKeydown"]))}}),de=c({__name:"SwitchThumb",props:{asChild:{type:Boolean},as:{default:"span"}},setup(t){const e=se();return T(),(a,n)=>{var l;return m(),y(i(F),{"data-state":(l=i(e).modelValue)!=null&&l.value?"checked":"unchecked","data-disabled":i(e).disabled.value?"":void 0,"as-child":a.asChild,as:a.as},{default:_(()=>[w(a.$slots,"default")]),_:3},8,["data-state","data-disabled","as-child","as"])}}}),ce=c({__name:"Checkbox",props:{modelValue:{type:Boolean,required:!0},modelModifiers:{}},emits:["update:modelValue"],setup(t){const e=M(t,"modelValue");return(a,n)=>(m(),y(i(ie),{modelValue:e.value,"onUpdate:modelValue":n[0]||(n[0]=l=>e.value=l),transition:"background duration-250 ease-in-out",outline:"focus-within:none",flex:"~",border:"neutral-300 dark:neutral-700 data-[state=checked]:primary-200 data-[state=unchecked]:neutral-300 focus-within:neutral-800",bg:"data-[state=checked]:primary-400 data-[state=unchecked]:neutral-300 data-[state=checked]:dark:primary-400/80 dark:data-[state=unchecked]:neutral-800",relative:"","h-7":"",w:"12.5","rounded-full":"",shadow:"sm focus-within:shadow-neutral-800 focus-within:[0_0_0_1px] "},{default:_(()=>[$(i(de),{"my-auto":"","size-6":"",flex:"","items-center":"","justify-center":"","translate-x":"0.5 data-[state=checked]:full","rounded-full":"","bg-white":"","text-xs":"","shadow-xl":"",transition:"transform duration-250 ease-in-out","will-change-transform":""})]),_:1},8,["modelValue"]))}}),me={flex:"~ col gap-4"},fe={flex:"~ row","items-center":"","gap-2":""},pe={flex:"1"},ve={class:"flex items-center gap-1 text-sm font-medium"},he={class:"text-xs text-neutral-500 dark:text-neutral-400"},Pe=c({__name:"FieldCheckbox",props:q({label:null,description:null},{modelValue:{type:Boolean,required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,a=M(t,"modelValue");return(n,l)=>(m(),g("label",me,[h("div",fe,[h("div",pe,[h("div",ve,V(e.label),1),h("div",he,V(e.description),1)]),$(ce,{modelValue:a.value,"onUpdate:modelValue":l[0]||(l[0]=o=>a.value=o)},null,8,["modelValue"])])]))}}),be=["min","max","step"],ye=c({__name:"Range",props:{modelValue:null,min:{default:0},max:{default:100},step:{default:1},disabled:{type:Boolean,default:!1},thumbColor:{default:"#9090906e"},trackColor:{default:"gray"},trackValueColor:{default:"red"}},emits:["update:modelValue"],setup(t,{emit:e}){const a=t,n=e,l=b(()=>a.min*1e4),o=b(()=>a.max*1e4),r=b(()=>a.step*1e4),s=x(),f=x(a.modelValue*1e4);A(f,d=>{n("update:modelValue",d/1e4),v()}),O(()=>{v()});function v(){s.value&&(s.value.style.setProperty("--value",s.value.value),s.value.style.setProperty("--min",s.value.min?s.value.min:a.min.toString()),s.value.style.setProperty("--max",s.value.max?s.value.max:a.max.toString()))}return(d,u)=>J((m(),g("input",{ref_key:"sliderRef",ref:s,"onUpdate:modelValue":u[0]||(u[0]=p=>f.value=p),type:"range",min:l.value,max:o.value,step:r.value,class:"form_input-range slider-progress",onInput:u[1]||(u[1]=p=>{p.target.style.setProperty("--value",p.target.value)})},null,40,be)),[[Q,f.value,void 0,{number:!0}]])}}),_e=B(ye,[["__scopeId","data-v-5db364fb"]]),xe={flex:"~ col gap-4"},ge={flex:"~ row","items-center":"","gap-2":""},Ve={flex:"1"},$e={class:"flex items-center gap-1 text-sm font-medium"},we={class:"text-xs text-neutral-500 dark:text-neutral-400"},ke={"font-mono":""},Ce={flex:"~ row","items-center":"","gap-2":""},Ae=c({__name:"FieldRange",props:q({min:null,max:null,step:null,label:null,description:null,formatValue:{type:Function}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,a=M(t,"modelValue");return(n,l)=>{var o;return m(),g("label",xe,[h("div",ge,[h("div",Ve,[h("div",$e,V(t.label),1),h("div",we,V(t.description),1)]),h("span",ke,V(((o=e.formatValue)==null?void 0:o.call(e,a.value))||a.value),1)]),h("div",Ce,[$(_e,{modelValue:a.value,"onUpdate:modelValue":l[0]||(l[0]=r=>a.value=r),min:t.min||0,max:t.max||1,step:t.step||.01,"w-full":""},null,8,["modelValue","min","max","step"])])])}}}),Ee=c({__name:"Volumed",props:{perspective:null,transform:null},setup(t){return(e,a)=>(m(),g("div",{class:"volumed",style:j({perspective:`${t.perspective}px`,transform:t.transform})},[w(e.$slots,"default",{},void 0,!0)],4))}}),Se=B(Ee,[["__scopeId","data-v-568551bc"]]),Me=c({__name:"CursorMomentum",props:{baseSpeed:{default:.1},friction:{default:.95},momentumFactor:{default:.005}},setup(t,{expose:e}){const a=t,n=x(1),l=x(0);let o=0;const r=E(()=>a.friction),s=E(()=>a.baseSpeed),f=E(()=>a.momentumFactor);function v(u){o||(o=u);const p=u-o;o=u,n.value=s.value+(n.value-s.value)*r.value,l.value+=n.value*p,requestAnimationFrame(v)}function d(u){const p=Math.sqrt(u.movementX**2+u.movementY**2);n.value+=p*f.value}return O(()=>{window.addEventListener("mousemove",d),requestAnimationFrame(v)}),Z(()=>{window.removeEventListener("mousemove",d)}),e({momentum:n,currentValue:l}),(u,p)=>w(u.$slots,"default",{momentum:n.value,currentValue:l.value})}}),Be=c({__name:"TestDummyMarkerFlat",props:{size:null},setup(t){return(e,a)=>(m(),g("div",{class:"test-dummy-flat",style:j({width:`${t.size}px`,height:`${t.size}px`})},a[0]||(a[0]=[h("div",{class:"marker"},null,-1)]),4))}}),je=B(Be,[["__scopeId","data-v-b4ef37ac"]]),qe=c({__name:"TestDummyMarker",setup(t){return(e,a)=>(m(),y(Me,{"base-speed":.1,friction:.95,"momentum-factor":5e-4},{default:_(({currentValue:n})=>[$(Se,{perspective:800,transform:"rotateX(45deg) translateY(3px)"},{default:_(()=>[$(je,{size:24,style:j({transform:`rotate(${n}deg)`})},null,8,["style"])]),_:2},1024)]),_:1}))}});export{Ae as _,Pe as a,qe as b}; diff --git a/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js b/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js similarity index 93% rename from assets/TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js rename to assets/TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js index dec323897cf3f14c403639afdd5e8b42ed6a15db..39cdcb3abce3b9ab86810afcc08f1f183dc37a4b 100644 --- a/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js +++ b/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js @@ -1 +1 @@ -import{d as T,x as l,o as m,bB as B,y as b,p as v}from"./index-rD0Uu1v9.js";const n="0px",W=T({__name:"TransitionVertical",props:{duration:{default:250},easingEnter:{default:"ease-in-out"},easingLeave:{default:"ease-in-out"},opacityClosed:{default:0},opacityOpened:{default:1}},setup(c){const r=c;function p(o){return{height:o.style.height,width:o.style.width,position:o.style.position,visibility:o.style.visibility,overflow:o.style.overflow,paddingTop:o.style.paddingTop,paddingBottom:o.style.paddingBottom,borderTopWidth:o.style.borderTopWidth,borderBottomWidth:o.style.borderBottomWidth,marginTop:o.style.marginTop,marginBottom:o.style.marginBottom}}function y(o,t){const{width:i}=getComputedStyle(o);o.style.width=i,o.style.position="absolute",o.style.visibility="hidden",o.style.height="";const{height:s}=getComputedStyle(o);return o.style.width=t.width,o.style.position=t.position,o.style.visibility=t.visibility,o.style.height=n,o.style.overflow="hidden",t.height&&t.height!==n?t.height:s}function h(o,t,i,s,d){const e=o.animate(s,d);o.style.height=t.height,e.onfinish=()=>{o.style.overflow=t.overflow,i()}}function g(o,t){return[{height:n,opacity:r.opacityClosed,paddingTop:n,paddingBottom:n,borderTopWidth:n,borderBottomWidth:n,marginTop:n,marginBottom:n},{height:o,opacity:r.opacityOpened,paddingTop:t.paddingTop,paddingBottom:t.paddingBottom,borderTopWidth:t.borderTopWidth,borderBottomWidth:t.borderBottomWidth,marginTop:t.marginTop,marginBottom:t.marginBottom}]}function u(o,t){const i=o,s=p(i),d=y(i,s),e=g(d,s),a={duration:r.duration,easing:r.easingEnter};h(i,s,t,e,a)}function f(o,t){const i=o,s=p(i),{height:d}=getComputedStyle(i);i.style.height=d,i.style.overflow="hidden";const e=g(d,s).reverse(),a={duration:r.duration,easing:r.easingLeave};h(i,s,t,e,a)}return(o,t)=>(m(),l(B,{css:!1,onEnter:u,onLeave:f},{default:b(()=>[v(o.$slots,"default")]),_:3}))}});export{W as _}; +import{d as T,x as l,o as m,bB as B,y as b,p as v}from"./index-Dlp4W1Zl.js";const n="0px",W=T({__name:"TransitionVertical",props:{duration:{default:250},easingEnter:{default:"ease-in-out"},easingLeave:{default:"ease-in-out"},opacityClosed:{default:0},opacityOpened:{default:1}},setup(c){const r=c;function p(o){return{height:o.style.height,width:o.style.width,position:o.style.position,visibility:o.style.visibility,overflow:o.style.overflow,paddingTop:o.style.paddingTop,paddingBottom:o.style.paddingBottom,borderTopWidth:o.style.borderTopWidth,borderBottomWidth:o.style.borderBottomWidth,marginTop:o.style.marginTop,marginBottom:o.style.marginBottom}}function y(o,t){const{width:i}=getComputedStyle(o);o.style.width=i,o.style.position="absolute",o.style.visibility="hidden",o.style.height="";const{height:s}=getComputedStyle(o);return o.style.width=t.width,o.style.position=t.position,o.style.visibility=t.visibility,o.style.height=n,o.style.overflow="hidden",t.height&&t.height!==n?t.height:s}function h(o,t,i,s,d){const e=o.animate(s,d);o.style.height=t.height,e.onfinish=()=>{o.style.overflow=t.overflow,i()}}function g(o,t){return[{height:n,opacity:r.opacityClosed,paddingTop:n,paddingBottom:n,borderTopWidth:n,borderBottomWidth:n,marginTop:n,marginBottom:n},{height:o,opacity:r.opacityOpened,paddingTop:t.paddingTop,paddingBottom:t.paddingBottom,borderTopWidth:t.borderTopWidth,borderBottomWidth:t.borderBottomWidth,marginTop:t.marginTop,marginBottom:t.marginBottom}]}function u(o,t){const i=o,s=p(i),d=y(i,s),e=g(d,s),a={duration:r.duration,easing:r.easingEnter};h(i,s,t,e,a)}function f(o,t){const i=o,s=p(i),{height:d}=getComputedStyle(i);i.style.height=d,i.style.overflow="hidden";const e=g(d,s).reverse(),a={duration:r.duration,easing:r.easingLeave};h(i,s,t,e,a)}return(o,t)=>(m(),l(B,{css:!1,onEnter:u,onLeave:f},{default:b(()=>[v(o.$slots,"default")]),_:3}))}});export{W as _}; diff --git a/assets/_...all_-CfLFDWc0.js b/assets/_...all_-xa5MzuBe.js similarity index 64% rename from assets/_...all_-CfLFDWc0.js rename to assets/_...all_-xa5MzuBe.js index ddcaee9a7fc3ed8dedc72ace8964eea2f20e2ac1..d75bd75a2b1662e3b5aaca815b95b222dbe362bf 100644 --- a/assets/_...all_-CfLFDWc0.js +++ b/assets/_...all_-xa5MzuBe.js @@ -1 +1 @@ -import{bn as e,c as n,o as c}from"./index-rD0Uu1v9.js";const o={};function _(t,r){return c(),n("div",null," 404 - Page not found ")}const s=e(o,[["render",_]]);export{s as default}; +import{bn as e,c as n,o as c}from"./index-Dlp4W1Zl.js";const o={};function _(t,r){return c(),n("div",null," 404 - Page not found ")}const s=e(o,[["render",_]]);export{s as default}; diff --git a/assets/audio-DinYnl_N.js b/assets/audio-Bsbq-iZ9.js similarity index 88% rename from assets/audio-DinYnl_N.js rename to assets/audio-Bsbq-iZ9.js index 3a1b0d4a89e2fac25973722237bce3e51f089850..4dca76d63e79b1ada2ac605c61253d39a6e06eeb 100644 --- a/assets/audio-DinYnl_N.js +++ b/assets/audio-Bsbq-iZ9.js @@ -1 +1 @@ -import{d as s,g as f,c as d,o as p,a as t}from"./index-rD0Uu1v9.js";const R=s({__name:"audio",setup(_){const a=f(),l=f();function u(o){var r,c,i;if(!o)return;const n=(c=(r=l.value)==null?void 0:r.files)==null?void 0:c[0];if(!n)return;const e=document.createElement("audio");(i=a.value)==null||i.appendChild(e),e.src=URL.createObjectURL(n),e.controls=!0,e.load(),e.play()}return(o,n)=>(p(),d("div",null,[t("div",null,[t("div",{ref_key:"containerRef",ref:a},null,512),t("input",{ref_key:"fileInputRef",ref:l,type:"file",onChange:u},null,544)])]))}});export{R as default}; +import{d as s,g as f,c as d,o as p,a as t}from"./index-Dlp4W1Zl.js";const R=s({__name:"audio",setup(_){const a=f(),l=f();function u(o){var r,c,i;if(!o)return;const n=(c=(r=l.value)==null?void 0:r.files)==null?void 0:c[0];if(!n)return;const e=document.createElement("audio");(i=a.value)==null||i.appendChild(e),e.src=URL.createObjectURL(n),e.controls=!0,e.load(),e.play()}return(o,n)=>(p(),d("div",null,[t("div",null,[t("div",{ref_key:"containerRef",ref:a},null,512),t("input",{ref_key:"fileInputRef",ref:l,type:"file",onChange:u},null,544)])]))}});export{R as default}; diff --git a/assets/cloudflare-workers-ai-DW44wYmt.js b/assets/cloudflare-workers-ai-DV3XjoGA.js similarity index 81% rename from assets/cloudflare-workers-ai-DW44wYmt.js rename to assets/cloudflare-workers-ai-DV3XjoGA.js index a02e98dd393a4ce9a26bf2f8c8a15c5f20873daa..c6e4e37dc0ca0b0ddac997cf0195b65078b6a199 100644 --- a/assets/cloudflare-workers-ai-DW44wYmt.js +++ b/assets/cloudflare-workers-ai-DV3XjoGA.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as V,bF as w,bG as y,x as k,o as I,i as x,bE as M,s as $,h as v,m as q,w as K,y as f,b as c,e as l}from"./index-rD0Uu1v9.js";import{u as P}from"./providers-Dg3FpvfZ.js";import{_ as z}from"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import{_ as A}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as B,a as C}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as N}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const R=V({__name:"ProviderAccountIdInput",props:w({placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(p){const r=p,u=y(p,"modelValue");return(n,e)=>(I(),k(z,{modelValue:u.value,"onUpdate:modelValue":e[0]||(e[0]=t=>u.value=t),label:r.label||"Account ID",description:r.description||"Account ID",placeholder:r.placeholder,required:r.required,type:"text"},null,8,["modelValue","label","description","placeholder","required"]))}}),a="cloudflare-workers-ai",j=V({__name:"cloudflare-workers-ai",setup(p){const{t:r}=x(),u=M(),n=P(),{providers:e}=$(n),t=v(()=>n.getProviderMetadata(a)),s=v({get:()=>{var o;return((o=e.value[a])==null?void 0:o.apiKey)||""},set:o=>{e.value[a]||(e.value[a]={}),e.value[a].apiKey=o}}),d=v({get:()=>{var o;return((o=e.value[a])==null?void 0:o.accountId)||""},set:o=>{e.value[a]||(e.value[a]={}),e.value[a].accountId=o}});q(()=>{var o,i;n.initializeProvider(a),s.value=((o=e.value[a])==null?void 0:o.apiKey)||"",d.value=((i=e.value[a])==null?void 0:i.accountId)||""}),K([s,d],()=>{e.value[a]={...e.value[a],apiKey:s.value,accountId:d.value}});function h(){var o;e.value[a]={...(o=t.value)==null?void 0:o.defaultOptions}}return(o,i)=>{var _,g;return I(),k(l(N),{"provider-name":(_=t.value)==null?void 0:_.localizedName,"provider-icon-color":(g=t.value)==null?void 0:g.iconColor,"on-back":()=>l(u).back()},{default:f(()=>[c(l(B),null,{default:f(()=>[c(l(C),{title:l(r)("settings.pages.providers.common.section.basic.title"),description:l(r)("settings.pages.providers.common.section.basic.description"),"on-reset":h},{default:f(()=>{var b;return[c(l(A),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=m=>s.value=m),"provider-name":(b=t.value)==null?void 0:b.localizedName,placeholder:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.api-key.placeholder")},null,8,["modelValue","provider-name","placeholder"]),c(l(R),{modelValue:d.value,"onUpdate:modelValue":i[1]||(i[1]=m=>d.value=m),label:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.account-id.label"),description:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.account-id.description"),placeholder:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.account-id.placeholder")},null,8,["modelValue","label","description","placeholder"])]}),_:1},8,["title","description"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{j as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as V,bF as w,bG as y,x as k,o as I,i as x,bE as M,s as $,h as v,m as q,w as K,y as f,b as c,e as l}from"./index-Dlp4W1Zl.js";import{u as P}from"./providers-BRCa7xUS.js";import{_ as z}from"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import{_ as A}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as B,a as C}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as N}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const R=V({__name:"ProviderAccountIdInput",props:w({placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(p){const r=p,u=y(p,"modelValue");return(n,e)=>(I(),k(z,{modelValue:u.value,"onUpdate:modelValue":e[0]||(e[0]=t=>u.value=t),label:r.label||"Account ID",description:r.description||"Account ID",placeholder:r.placeholder,required:r.required,type:"text"},null,8,["modelValue","label","description","placeholder","required"]))}}),a="cloudflare-workers-ai",j=V({__name:"cloudflare-workers-ai",setup(p){const{t:r}=x(),u=M(),n=P(),{providers:e}=$(n),t=v(()=>n.getProviderMetadata(a)),s=v({get:()=>{var o;return((o=e.value[a])==null?void 0:o.apiKey)||""},set:o=>{e.value[a]||(e.value[a]={}),e.value[a].apiKey=o}}),d=v({get:()=>{var o;return((o=e.value[a])==null?void 0:o.accountId)||""},set:o=>{e.value[a]||(e.value[a]={}),e.value[a].accountId=o}});q(()=>{var o,i;n.initializeProvider(a),s.value=((o=e.value[a])==null?void 0:o.apiKey)||"",d.value=((i=e.value[a])==null?void 0:i.accountId)||""}),K([s,d],()=>{e.value[a]={...e.value[a],apiKey:s.value,accountId:d.value}});function h(){var o;e.value[a]={...(o=t.value)==null?void 0:o.defaultOptions}}return(o,i)=>{var _,g;return I(),k(l(N),{"provider-name":(_=t.value)==null?void 0:_.localizedName,"provider-icon-color":(g=t.value)==null?void 0:g.iconColor,"on-back":()=>l(u).back()},{default:f(()=>[c(l(B),null,{default:f(()=>[c(l(C),{title:l(r)("settings.pages.providers.common.section.basic.title"),description:l(r)("settings.pages.providers.common.section.basic.description"),"on-reset":h},{default:f(()=>{var b;return[c(l(A),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=m=>s.value=m),"provider-name":(b=t.value)==null?void 0:b.localizedName,placeholder:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.api-key.placeholder")},null,8,["modelValue","provider-name","placeholder"]),c(l(R),{modelValue:d.value,"onUpdate:modelValue":i[1]||(i[1]=m=>d.value=m),label:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.account-id.label"),description:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.account-id.description"),placeholder:l(r)("settings.pages.providers.provider.cloudflare-workers-ai.fields.field.account-id.placeholder")},null,8,["modelValue","label","description","placeholder"])]}),_:1},8,["title","description"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{j as default}; diff --git a/assets/consciousness-B-O47Lyx.js b/assets/consciousness-CnU1Bi0O.js similarity index 90% rename from assets/consciousness-B-O47Lyx.js rename to assets/consciousness-CnU1Bi0O.js index c0b1c9f85d3928c24367009e392044550e038aeb..357274f1f78a5a34eefb5db8f72a4099ee1f940b 100644 --- a/assets/consciousness-B-O47Lyx.js +++ b/assets/consciousness-CnU1Bi0O.js @@ -1 +1 @@ -import{f as P,cb as n,g as M,h as r,w as L}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";const h=P("consciousness",()=>{const o=w(),s=n("settings/consciousness/active-provider",""),c=n("settings/consciousness/active-model",""),d=n("settings/consciousness/active-custom-model",""),l=M({}),i=M(""),m=r(()=>{var e;return((e=o.getProviderMetadata(s.value))==null?void 0:e.capabilities.listModels)!==void 0}),a=r(()=>o.getModelsForProvider(s.value)),f=r(()=>o.isLoadingModels[s.value]||!1),g=r(()=>o.modelLoadError[s.value]||null),p=r(()=>{if(!i.value.trim())return a.value;const e=i.value.toLowerCase().trim();return a.value.filter(t=>t.name.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||t.description&&t.description.toLowerCase().includes(e))});function u(){c.value="",d.value="",l.value={},i.value=""}async function v(e){var t;e&&((t=o.getProviderMetadata(s.value))==null?void 0:t.capabilities.listModels)!==void 0&&o.getModelsForProvider(e).length===0&&await o.fetchModelsForProvider(e)}return L(s,async e=>{await v(e),u()}),{activeProvider:s,activeModel:c,customModelName:d,expandedDescriptions:l,modelSearchQuery:i,supportsModelListing:m,providerModels:a,isLoadingActiveProviderModels:f,activeProviderModelError:g,filteredModels:p,resetModelSelection:u,loadModelsForProvider:v}});export{h as u}; +import{f as P,cb as n,g as M,h as r,w as L}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";const h=P("consciousness",()=>{const o=w(),s=n("settings/consciousness/active-provider",""),c=n("settings/consciousness/active-model",""),d=n("settings/consciousness/active-custom-model",""),l=M({}),i=M(""),m=r(()=>{var e;return((e=o.getProviderMetadata(s.value))==null?void 0:e.capabilities.listModels)!==void 0}),a=r(()=>o.getModelsForProvider(s.value)),f=r(()=>o.isLoadingModels[s.value]||!1),g=r(()=>o.modelLoadError[s.value]||null),p=r(()=>{if(!i.value.trim())return a.value;const e=i.value.toLowerCase().trim();return a.value.filter(t=>t.name.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||t.description&&t.description.toLowerCase().includes(e))});function u(){c.value="",d.value="",l.value={},i.value=""}async function v(e){var t;e&&((t=o.getProviderMetadata(s.value))==null?void 0:t.capabilities.listModels)!==void 0&&o.getModelsForProvider(e).length===0&&await o.fetchModelsForProvider(e)}return L(s,async e=>{await v(e),u()}),{activeProvider:s,activeModel:c,customModelName:d,expandedDescriptions:l,modelSearchQuery:i,supportsModelListing:m,providerModels:a,isLoadingActiveProviderModels:f,activeProviderModelError:g,filteredModels:p,resetModelSelection:u,loadModelsForProvider:v}});export{h as u}; diff --git a/assets/consciousness-B3RqLnFs.js b/assets/consciousness-iz2nv6B3.js similarity index 95% rename from assets/consciousness-B3RqLnFs.js rename to assets/consciousness-iz2nv6B3.js index a89484711774e19e58e336fe2c164ae56a178678..01106df83b83858166b8eced1eaa4dfc1b6021b5 100644 --- a/assets/consciousness-B3RqLnFs.js +++ b/assets/consciousness-iz2nv6B3.js @@ -1 +1 @@ -import{d as L,s as b,i as U,bE as B,m as q,bw as z,c as r,o as l,A as h,a as e,e as s,D as n,C as f,bx as k,by as E,b as T,y as A,bo as F,x as y,ad as u,bJ as Q}from"./index-rD0Uu1v9.js";import{R as j,a as G}from"./RadioCardDetailManySelect-cGsz75Pf.js";import"./live2d-zip-loader-BdiFCiUD.js";import{u as I}from"./consciousness-B-O47Lyx.js";import{u as J}from"./providers-Dg3FpvfZ.js";import{b as w}from"./route-block-B_A1xBdJ.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const $={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},H={relative:""},K={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},O={text:"neutral-300 dark:neutral-500","text-nowrap":""},W={"text-nowrap":"","text-3xl":"","font-semibold":""},X={bg:"neutral-50 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4"},Y={flex:"~ col gap-4"},Z={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-500"},ee={text:"neutral-400 dark:neutral-400"},se={"max-w-full":""},te={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},oe={key:1},ne={key:0},ie={flex:"~ col gap-4"},le={class:"text-lg md:text-2xl"},re={text:"neutral-400 dark:neutral-400"},de={key:0,class:"flex items-center justify-center py-4"},ae={key:1,class:"flex items-center gap-3 border border-red-200 rounded-lg bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20"},ce={class:"flex flex-col"},ue={class:"font-medium"},pe={class:"text-sm text-red-600 dark:text-red-400"},me={key:2,class:"flex items-center gap-3 border border-amber-200 rounded-lg bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},xe={class:"flex flex-col"},ve={class:"font-medium"},ge={class:"text-sm text-amber-600 dark:text-amber-400"},_e={key:1},be={flex:"~ col gap-4"},he={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},fe={text:"neutral-400 dark:neutral-500"},ke={class:"bg-primary-50 border-primary-200 dark:bg-primary-900/20 dark:border-primary-800 flex items-center gap-3 border rounded-lg p-4"},ye={class:"flex flex-col"},we={class:"font-medium"},Me={class:"dark:text-primary-400 text-primary-600 text-sm"},Ce={class:"mt-2"},Ve={class:"mb-1 block text-sm font-medium"},Pe=["placeholder"],Se=L({__name:"consciousness",setup(Ne){const M=J(),m=I(),{availableProviders:C,availableTextGenerationsProvidersMetadata:V}=b(M),{activeProvider:d,activeModel:a,customModelName:P,modelSearchQuery:c,supportsModelListing:x,providerModels:p,isLoadingActiveProviderModels:v,activeProviderModelError:g}=b(m),{t:o}=U(),S=B();q(async()=>{await m.loadModelsForProvider(d.value)});function N(_){P.value=_}return(_,t)=>{const R=z("motion");return l(),r(k,null,[h((l(),r("div",$,[e("button",{onClick:t[0]||(t[0]=i=>s(S).back())},t[5]||(t[5]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-xl":""},null,-1)])),e("h1",H,[e("div",K,[e("span",O,n(s(o)("settings.pages.modules.title")),1)]),e("div",W,n(s(o)("settings.pages.modules.consciousness.title")),1)])])),[[R]]),e("div",X,[e("div",null,[e("div",Y,[e("div",null,[e("h2",Z,n(s(o)("settings.pages.providers.title")),1),e("div",ee,[e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.description")),1)])]),e("div",se,[s(C).length>0?(l(),r("fieldset",te,[(l(!0),r(k,null,E(s(V),i=>(l(),y(s(G),{id:i.id,key:i.id,modelValue:s(d),"onUpdate:modelValue":t[1]||(t[1]=D=>u(d)?d.value=D:null),name:"provider",value:i.id,title:i.localizedName,description:i.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(l(),r("div",oe,[T(s(F),{class:"flex items-center gap-3 rounded-lg p-4",border:"2 dashed neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-800",transition:"colors duration-200 ease-in-out",to:"/settings/providers"},{default:A(()=>t[6]||(t[6]=[e("div",{"i-solar:warning-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1),e("div",{class:"flex flex-col"},[e("span",{class:"font-medium"},"No Providers Configured"),e("span",{class:"text-sm text-neutral-400 dark:text-neutral-500"},"Click here to set up your LLM providers")],-1),e("div",{"i-solar:arrow-right-line-duotone":"",class:"ml-auto text-xl text-neutral-400 dark:text-neutral-500"},null,-1)])),_:1})]))])])]),s(d)&&s(x)?(l(),r("div",ne,[e("div",ie,[e("div",null,[e("h2",le,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",re,[e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),s(v)?(l(),r("div",de,[t[7]||(t[7]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):s(g)?(l(),r("div",ae,[t[8]||(t[8]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",ce,[e("span",ue,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",pe,n(s(g)),1)])])):s(p).length===0&&!s(v)?(l(),r("div",me,[t[9]||(t[9]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",xe,[e("span",ve,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",ge,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):s(p).length>0?(l(),y(s(j),{key:3,modelValue:s(a),"onUpdate:modelValue":t[2]||(t[2]=i=>u(a)?a.value=i:null),"search-query":s(c),"onUpdate:searchQuery":t[3]||(t[3]=i=>u(c)?c.value=i:null),items:s(p),searchable:!0,"search-placeholder":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:s(c)}),"search-results-text":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":N},null,8,["modelValue","search-query","items","search-placeholder","search-no-results-title","search-no-results-description","search-results-text","custom-input-placeholder","expand-button-text","collapse-button-text"])):f("",!0)])])):s(d)&&!s(x)?(l(),r("div",_e,[e("div",be,[e("div",null,[e("h2",he,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",fe,[e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),e("div",ke,[t[10]||(t[10]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-primary-500 dark:text-primary-400 text-2xl"},null,-1)),e("div",ye,[e("span",we,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported")),1),e("span",Me,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported_description")),1)])]),e("div",Ce,[e("label",Ve,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_name")),1),h(e("input",{"onUpdate:modelValue":t[4]||(t[4]=i=>u(a)?a.value=i:null),type:"text",class:"w-full border border-neutral-300 rounded bg-white px-3 py-2 dark:border-neutral-700 dark:bg-neutral-900",placeholder:s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_placeholder")},null,8,Pe),[[Q,s(a)]])])])])):f("",!0)]),t[11]||(t[11]=e("div",{text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},[e("div",{text:"40","i-lucide:ghost":""})],-1))],64)}}});typeof w=="function"&&w(Se);export{Se as default}; +import{d as L,s as b,i as U,bE as B,m as q,bw as z,c as r,o as l,A as h,a as e,e as s,D as n,C as f,bx as k,by as E,b as T,y as A,bo as F,x as y,ad as u,bJ as Q}from"./index-Dlp4W1Zl.js";import{R as j,a as G}from"./RadioCardDetailManySelect-rPQeY4V8.js";import"./live2d-zip-loader-C5j9stxV.js";import{u as I}from"./consciousness-CnU1Bi0O.js";import{u as J}from"./providers-BRCa7xUS.js";import{b as w}from"./route-block-B_A1xBdJ.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const $={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},H={relative:""},K={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},O={text:"neutral-300 dark:neutral-500","text-nowrap":""},W={"text-nowrap":"","text-3xl":"","font-semibold":""},X={bg:"neutral-50 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4"},Y={flex:"~ col gap-4"},Z={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-500"},ee={text:"neutral-400 dark:neutral-400"},se={"max-w-full":""},te={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},oe={key:1},ne={key:0},ie={flex:"~ col gap-4"},le={class:"text-lg md:text-2xl"},re={text:"neutral-400 dark:neutral-400"},de={key:0,class:"flex items-center justify-center py-4"},ae={key:1,class:"flex items-center gap-3 border border-red-200 rounded-lg bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20"},ce={class:"flex flex-col"},ue={class:"font-medium"},pe={class:"text-sm text-red-600 dark:text-red-400"},me={key:2,class:"flex items-center gap-3 border border-amber-200 rounded-lg bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},xe={class:"flex flex-col"},ve={class:"font-medium"},ge={class:"text-sm text-amber-600 dark:text-amber-400"},_e={key:1},be={flex:"~ col gap-4"},he={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},fe={text:"neutral-400 dark:neutral-500"},ke={class:"bg-primary-50 border-primary-200 dark:bg-primary-900/20 dark:border-primary-800 flex items-center gap-3 border rounded-lg p-4"},ye={class:"flex flex-col"},we={class:"font-medium"},Me={class:"dark:text-primary-400 text-primary-600 text-sm"},Ce={class:"mt-2"},Ve={class:"mb-1 block text-sm font-medium"},Pe=["placeholder"],Se=L({__name:"consciousness",setup(Ne){const M=J(),m=I(),{availableProviders:C,availableTextGenerationsProvidersMetadata:V}=b(M),{activeProvider:d,activeModel:a,customModelName:P,modelSearchQuery:c,supportsModelListing:x,providerModels:p,isLoadingActiveProviderModels:v,activeProviderModelError:g}=b(m),{t:o}=U(),S=B();q(async()=>{await m.loadModelsForProvider(d.value)});function N(_){P.value=_}return(_,t)=>{const R=z("motion");return l(),r(k,null,[h((l(),r("div",$,[e("button",{onClick:t[0]||(t[0]=i=>s(S).back())},t[5]||(t[5]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-xl":""},null,-1)])),e("h1",H,[e("div",K,[e("span",O,n(s(o)("settings.pages.modules.title")),1)]),e("div",W,n(s(o)("settings.pages.modules.consciousness.title")),1)])])),[[R]]),e("div",X,[e("div",null,[e("div",Y,[e("div",null,[e("h2",Z,n(s(o)("settings.pages.providers.title")),1),e("div",ee,[e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.description")),1)])]),e("div",se,[s(C).length>0?(l(),r("fieldset",te,[(l(!0),r(k,null,E(s(V),i=>(l(),y(s(G),{id:i.id,key:i.id,modelValue:s(d),"onUpdate:modelValue":t[1]||(t[1]=D=>u(d)?d.value=D:null),name:"provider",value:i.id,title:i.localizedName,description:i.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(l(),r("div",oe,[T(s(F),{class:"flex items-center gap-3 rounded-lg p-4",border:"2 dashed neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-800",transition:"colors duration-200 ease-in-out",to:"/settings/providers"},{default:A(()=>t[6]||(t[6]=[e("div",{"i-solar:warning-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1),e("div",{class:"flex flex-col"},[e("span",{class:"font-medium"},"No Providers Configured"),e("span",{class:"text-sm text-neutral-400 dark:text-neutral-500"},"Click here to set up your LLM providers")],-1),e("div",{"i-solar:arrow-right-line-duotone":"",class:"ml-auto text-xl text-neutral-400 dark:text-neutral-500"},null,-1)])),_:1})]))])])]),s(d)&&s(x)?(l(),r("div",ne,[e("div",ie,[e("div",null,[e("h2",le,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",re,[e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),s(v)?(l(),r("div",de,[t[7]||(t[7]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):s(g)?(l(),r("div",ae,[t[8]||(t[8]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",ce,[e("span",ue,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",pe,n(s(g)),1)])])):s(p).length===0&&!s(v)?(l(),r("div",me,[t[9]||(t[9]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",xe,[e("span",ve,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",ge,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):s(p).length>0?(l(),y(s(j),{key:3,modelValue:s(a),"onUpdate:modelValue":t[2]||(t[2]=i=>u(a)?a.value=i:null),"search-query":s(c),"onUpdate:searchQuery":t[3]||(t[3]=i=>u(c)?c.value=i:null),items:s(p),searchable:!0,"search-placeholder":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:s(c)}),"search-results-text":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":N},null,8,["modelValue","search-query","items","search-placeholder","search-no-results-title","search-no-results-description","search-results-text","custom-input-placeholder","expand-button-text","collapse-button-text"])):f("",!0)])])):s(d)&&!s(x)?(l(),r("div",_e,[e("div",be,[e("div",null,[e("h2",he,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",fe,[e("span",null,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),e("div",ke,[t[10]||(t[10]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-primary-500 dark:text-primary-400 text-2xl"},null,-1)),e("div",ye,[e("span",we,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported")),1),e("span",Me,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported_description")),1)])]),e("div",Ce,[e("label",Ve,n(s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_name")),1),h(e("input",{"onUpdate:modelValue":t[4]||(t[4]=i=>u(a)?a.value=i:null),type:"text",class:"w-full border border-neutral-300 rounded bg-white px-3 py-2 dark:border-neutral-700 dark:bg-neutral-900",placeholder:s(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_placeholder")},null,8,Pe),[[Q,s(a)]])])])])):f("",!0)]),t[11]||(t[11]=e("div",{text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},[e("div",{text:"40","i-lucide:ghost":""})],-1))],64)}}});typeof w=="function"&&w(Se);export{Se as default}; diff --git a/assets/deepseek-C0RKjeMo.js b/assets/deepseek-CjDfnLNQ.js similarity index 67% rename from assets/deepseek-C0RKjeMo.js rename to assets/deepseek-CjDfnLNQ.js index 694c6f7b4a5d55f3efc1eaf7509c8ecaf0b07fb0..083b7c3144ea52b85b277b66a34fc3769012a88e 100644 --- a/assets/deepseek-C0RKjeMo.js +++ b/assets/deepseek-CjDfnLNQ.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as k,i as U,bE as V,s as y,h as c,m as $,w as K,x as h,o as x,y as p,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="deepseek",H=k({__name:"deepseek",setup(S){const{t:d}=U(),_=V(),m=w(),{providers:o}=y(m),n=c(()=>m.getProviderMetadata(a)),r=c({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),i=c({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,s;m.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",i.value=((s=o.value[a])==null?void 0:s.baseUrl)||""}),K([r,i],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:i.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,s)=>{var v,f;return x(),h(t(R),{"provider-name":(v=n.value)==null?void 0:v.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":s[0]||(s[0]=g=>r.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:i.value,"onUpdate:modelValue":s[1]||(s[1]=u=>i.value=u),placeholder:"https://api.deepseek.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as k,i as U,bE as V,s as y,h as c,m as $,w as K,x as h,o as x,y as p,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="deepseek",H=k({__name:"deepseek",setup(S){const{t:d}=U(),_=V(),m=w(),{providers:o}=y(m),n=c(()=>m.getProviderMetadata(a)),r=c({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),i=c({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,s;m.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",i.value=((s=o.value[a])==null?void 0:s.baseUrl)||""}),K([r,i],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:i.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,s)=>{var v,f;return x(),h(t(R),{"provider-name":(v=n.value)==null?void 0:v.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":s[0]||(s[0]=g=>r.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:i.value,"onUpdate:modelValue":s[1]||(s[1]=u=>i.value=u),placeholder:"https://api.deepseek.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; diff --git a/assets/default-Dqf43m-t.js b/assets/default-BiDUV3xY.js similarity index 89% rename from assets/default-Dqf43m-t.js rename to assets/default-BiDUV3xY.js index 510c064d58c92e42b32b3c2583917069e1c92917..143ac307138fc1f2bd69463198e208d79c018a72 100644 --- a/assets/default-Dqf43m-t.js +++ b/assets/default-BiDUV3xY.js @@ -1 +1 @@ -import{d as n,u as r,c,a,b as t,e,n as i,R as m,o as l}from"./index-rD0Uu1v9.js";import{H as x}from"./HeaderLink-0aZMXKsY.js";const f={"mb-4":"","w-full":"","gap-2":"",class:"px-0 py-1 md:px-3 md:py-3"},_={class:"px-3 py-2 md:px-5 md:py-5",flex:"~ col gap-4","mx-auto":"","max-w-screen-xl":""},$=n({__name:"default",setup(u){const{top:o,right:p,bottom:s,left:d}=r();return(g,y)=>(l(),c("div",{"p-2":"",style:i({paddingTop:`${e(o)}px`,paddingRight:`${e(p)}px`,paddingBottom:`${e(s)}px`,paddingLeft:`${e(d)}px`})},[a("div",f,[t(x)]),a("div",_,[t(e(m))])],4))}});export{$ as default}; +import{d as n,u as r,c,a,b as t,e,n as i,R as m,o as l}from"./index-Dlp4W1Zl.js";import{H as x}from"./HeaderLink-Dg_3MlXg.js";const f={"mb-4":"","w-full":"","gap-2":"",class:"px-0 py-1 md:px-3 md:py-3"},_={class:"px-3 py-2 md:px-5 md:py-5",flex:"~ col gap-4","mx-auto":"","max-w-screen-xl":""},$=n({__name:"default",setup(u){const{top:o,right:p,bottom:s,left:d}=r();return(g,y)=>(l(),c("div",{"p-2":"",style:i({paddingTop:`${e(o)}px`,paddingRight:`${e(p)}px`,paddingBottom:`${e(s)}px`,paddingLeft:`${e(d)}px`})},[a("div",f,[t(x)]),a("div",_,[t(e(m))])],4))}});export{$ as default}; diff --git a/assets/default-node-CM_FKz7Y.js b/assets/default-node-BIhtlSJe.js similarity index 89% rename from assets/default-node-CM_FKz7Y.js rename to assets/default-node-BIhtlSJe.js index 37640a1ba3de4792ffede44d2c07c22f87d03358..db46c5585966df515737dbe33956a586a9fa07a6 100644 --- a/assets/default-node-CM_FKz7Y.js +++ b/assets/default-node-BIhtlSJe.js @@ -1 +1 @@ -import{cq as t}from"./index-rD0Uu1v9.js";async function s(){const{createRequire:a}=await t(async()=>{const{createRequire:o}=await import("./__vite-browser-external-FmFgRqLi.js");return{createRequire:o}},[]),{dirname:n,resolve:e}=await t(async()=>{const{dirname:o,resolve:c}=await import("./__vite-browser-external-FmFgRqLi.js");return{dirname:o,resolve:c}},[]),d=a(import.meta.url),r=n(d.resolve("@duckdb/duckdb-wasm"));return{mvp:{mainModule:e(r,"./duckdb-mvp.wasm"),mainWorker:e(r,"./duckdb-node-mvp.worker.cjs")},eh:{mainModule:e(r,"./duckdb-eh.wasm"),mainWorker:e(r,"./duckdb-node-eh.worker.cjs")}}}export{s as getBundles}; +import{cq as t}from"./index-Dlp4W1Zl.js";async function s(){const{createRequire:a}=await t(async()=>{const{createRequire:o}=await import("./__vite-browser-external-FmFgRqLi.js");return{createRequire:o}},[]),{dirname:n,resolve:e}=await t(async()=>{const{dirname:o,resolve:c}=await import("./__vite-browser-external-FmFgRqLi.js");return{dirname:o,resolve:c}},[]),d=a(import.meta.url),r=n(d.resolve("@duckdb/duckdb-wasm"));return{mvp:{mainModule:e(r,"./duckdb-mvp.wasm"),mainWorker:e(r,"./duckdb-node-mvp.worker.cjs")},eh:{mainModule:e(r,"./duckdb-eh.wasm"),mainWorker:e(r,"./duckdb-node-eh.worker.cjs")}}}export{s as getBundles}; diff --git a/assets/delays-BG_vAngQ.js b/assets/delays-Cwu4yMJH.js similarity index 82% rename from assets/delays-BG_vAngQ.js rename to assets/delays-Cwu4yMJH.js index 21ff01eb4886d262cc09154da7a10b0c794a33ef..9f5b340bb239d9dbf6117e3548c70ab896406876 100644 --- a/assets/delays-BG_vAngQ.js +++ b/assets/delays-Cwu4yMJH.js @@ -1 +1 @@ -import{b as v,_,l as b}from"./queues-kGVt0l-U.js";import"./live2d-zip-loader-BdiFCiUD.js";import{d as k,g as d,c as s,o as l,a as e,b as y,e as x,D as i,bx as f,by as p}from"./index-rD0Uu1v9.js";import"./index-0_JGTbws.js";import"./queue-EbaGahVd.js";const z={flex:"","flex-col":"","gap-2":"","p-2":""},w={flex:"","flex-row":"","gap-2":""},h={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},M={"w-full":"",flex:"","flex-row":"","gap-4":""},V={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},D={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},N=k({__name:"delays",setup(E){const t=d(""),m=d([]),c=d([]),r=d(!1),u=v();u.onHandlerEvent("delay",a=>{c.value.push(a)});function g(){r.value=!0;const a=t.value.split("");for(const n of a)u.add(n);u.add(b),t.value="",r.value=!1}return(a,n)=>(l(),s("div",z,[e("div",w,[y(x(_),{modelValue:t.value,"onUpdate:modelValue":n[0]||(n[0]=o=>t.value=o),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:g},null,8,["modelValue"]),e("button",h,i(r.value?"Processing...":"Send"),1)]),e("div",M,[e("div",V,[n[1]||(n[1]=e("h3",{"font-semibold":""}," Emotion Message ",-1)),(l(!0),s(f,null,p(m.value,o=>(l(),s("div",{key:o},[e("div",null,i(o),1)]))),128))]),e("div",D,[n[2]||(n[2]=e("h3",{"font-semibold":""}," Delays ",-1)),(l(!0),s(f,null,p(c.value,o=>(l(),s("div",{key:o},[e("div",null,i(o)+"s",1)]))),128))])])]))}});export{N as default}; +import{b as v,_,l as b}from"./queues-CJq1hDiQ.js";import"./live2d-zip-loader-C5j9stxV.js";import{d as k,g as d,c as s,o as l,a as e,b as y,e as x,D as i,bx as f,by as p}from"./index-Dlp4W1Zl.js";import"./index-YJa3XIzO.js";import"./queue-DW8o1RLT.js";const z={flex:"","flex-col":"","gap-2":"","p-2":""},w={flex:"","flex-row":"","gap-2":""},h={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},M={"w-full":"",flex:"","flex-row":"","gap-4":""},V={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},D={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},N=k({__name:"delays",setup(E){const t=d(""),m=d([]),c=d([]),r=d(!1),u=v();u.onHandlerEvent("delay",a=>{c.value.push(a)});function g(){r.value=!0;const a=t.value.split("");for(const n of a)u.add(n);u.add(b),t.value="",r.value=!1}return(a,n)=>(l(),s("div",z,[e("div",w,[y(x(_),{modelValue:t.value,"onUpdate:modelValue":n[0]||(n[0]=o=>t.value=o),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:g},null,8,["modelValue"]),e("button",h,i(r.value?"Processing...":"Send"),1)]),e("div",M,[e("div",V,[n[1]||(n[1]=e("h3",{"font-semibold":""}," Emotion Message ",-1)),(l(!0),s(f,null,p(m.value,o=>(l(),s("div",{key:o},[e("div",null,i(o),1)]))),128))]),e("div",D,[n[2]||(n[2]=e("h3",{"font-semibold":""}," Delays ",-1)),(l(!0),s(f,null,p(c.value,o=>(l(),s("div",{key:o},[e("div",null,i(o)+"s",1)]))),128))])])]))}});export{N as default}; diff --git a/assets/elevenlabs-BwDmvV0f.js b/assets/elevenlabs-3ONCU5wo.js similarity index 56% rename from assets/elevenlabs-BwDmvV0f.js rename to assets/elevenlabs-3ONCU5wo.js index ab3dcac44630efc8f0e3f6fbd477f043ee1ebb3e..806ac21038bdbf1a97727115a7dd654b8271ab6c 100644 --- a/assets/elevenlabs-BwDmvV0f.js +++ b/assets/elevenlabs-3ONCU5wo.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as y,s as S,h as i,x as w,o as k,y as u,b as d,e as r}from"./index-rD0Uu1v9.js";import{u as x}from"./providers-Dg3FpvfZ.js";import{u as C}from"./speech-CUKri9wm.js";import{_ as B,a as L,b as V}from"./SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-UpCqB8UJ.js";import"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";const t="elevenlabs",v="eleven_multilingual_v2",j=y({__name:"elevenlabs",setup(P){const n={similarityBoost:.75,stability:.5,speed:1,style:0,useSpeakerBoost:!0},a=C(),s=x(),{providers:m}=S(s),f=i(()=>{var e;return!!((e=m.value[t])!=null&&e.apiKey)}),g=i(()=>a.availableVoices[t]||[]),h=i(()=>a.availableLanguages);async function _(e,l,p){const o=s.getProviderInstance(t);if(!o)throw new Error("Failed to initialize speech provider");const c=s.getProviderConfig(t),b=c.model||v;return await a.speech(o,b,e,l,{...c,...n})}return(e,l)=>(k(),w(r(V),{"provider-id":t,"default-model":v,"additional-settings":n},{"voice-settings":u(({voiceSettings:p,updateVoiceSettings:o})=>[d(r(L),{settings:p,"show-similarity-boost":!0,"show-stability":!0,"show-speed":!0,"show-style":!0,"show-speaker-boost":!0,onUpdate:o},null,8,["settings","onUpdate"])]),playground:u(()=>[d(r(B),{"available-voices":g.value,"available-languages":h.value,"generate-speech":_,"api-key-configured":f.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","available-languages","api-key-configured"])]),_:1}))}});export{j as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as y,s as S,h as i,x as w,o as k,y as u,b as d,e as r}from"./index-Dlp4W1Zl.js";import{u as x}from"./providers-BRCa7xUS.js";import{u as C}from"./speech-DU07zXBj.js";import{_ as B,a as L,b as V}from"./SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-CgsOdTr3.js";import"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";const t="elevenlabs",v="eleven_multilingual_v2",j=y({__name:"elevenlabs",setup(P){const n={similarityBoost:.75,stability:.5,speed:1,style:0,useSpeakerBoost:!0},a=C(),s=x(),{providers:m}=S(s),f=i(()=>{var e;return!!((e=m.value[t])!=null&&e.apiKey)}),g=i(()=>a.availableVoices[t]||[]),h=i(()=>a.availableLanguages);async function _(e,l,p){const o=s.getProviderInstance(t);if(!o)throw new Error("Failed to initialize speech provider");const c=s.getProviderConfig(t),b=c.model||v;return await a.speech(o,b,e,l,{...c,...n})}return(e,l)=>(k(),w(r(V),{"provider-id":t,"default-model":v,"additional-settings":n},{"voice-settings":u(({voiceSettings:p,updateVoiceSettings:o})=>[d(r(L),{settings:p,"show-similarity-boost":!0,"show-stability":!0,"show-speed":!0,"show-style":!0,"show-speaker-boost":!0,onUpdate:o},null,8,["settings","onUpdate"])]),playground:u(()=>[d(r(B),{"available-voices":g.value,"available-languages":h.value,"generate-speech":_,"api-key-configured":f.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","available-languages","api-key-configured"])]),_:1}))}});export{j as default}; diff --git a/assets/emotions-cpITk8zy.js b/assets/emotions-D6mNjsWQ.js similarity index 82% rename from assets/emotions-cpITk8zy.js rename to assets/emotions-D6mNjsWQ.js index e30a3d352916ad58e219cbca0d3c059ca336cb86..3cfe87b3c1a70cb6008ab0dccff7910e6934d7e4 100644 --- a/assets/emotions-cpITk8zy.js +++ b/assets/emotions-D6mNjsWQ.js @@ -1 +1 @@ -import{a as _,_ as b,l as k}from"./queues-kGVt0l-U.js";import"./live2d-zip-loader-BdiFCiUD.js";import{d as x,g as u,c as s,o as t,a as e,b as z,e as h,D as i,bx as f,by as m}from"./index-rD0Uu1v9.js";import{u as w}from"./queue-EbaGahVd.js";const y={flex:"","flex-col":"","gap-2":"","p-2":""},M={flex:"","flex-row":"","gap-2":""},V={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},E={"w-full":"",flex:"","flex-row":"","gap-4":""},Q={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},S={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},N=x({__name:"emotions",setup(B){const l=u(""),p=u([]),r=u([]),d=u(!1),g=w({handlers:[async a=>{r.value.push(a.data)}]}),c=_(g);function v(){d.value=!0;const a=l.value.split("");for(const o of a)c.add(o);c.add(k),l.value="",d.value=!1}return(a,o)=>(t(),s("div",y,[e("div",M,[z(h(b),{modelValue:l.value,"onUpdate:modelValue":o[0]||(o[0]=n=>l.value=n),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:v},null,8,["modelValue"]),e("button",V,i(d.value?"Processing...":"Send"),1)]),e("div",E,[e("div",Q,[o[1]||(o[1]=e("h3",{"font-semibold":""}," Messages ",-1)),(t(!0),s(f,null,m(p.value,n=>(t(),s("div",{key:n},[e("div",null,i(n),1)]))),128))]),e("div",S,[o[2]||(o[2]=e("h3",{"font-semibold":""}," Emotions ",-1)),(t(!0),s(f,null,m(r.value,n=>(t(),s("div",{key:n},[e("div",null,i(n),1)]))),128))])])]))}});export{N as default}; +import{a as _,_ as b,l as k}from"./queues-CJq1hDiQ.js";import"./live2d-zip-loader-C5j9stxV.js";import{d as x,g as u,c as s,o as t,a as e,b as z,e as h,D as i,bx as f,by as m}from"./index-Dlp4W1Zl.js";import{u as w}from"./queue-DW8o1RLT.js";const y={flex:"","flex-col":"","gap-2":"","p-2":""},M={flex:"","flex-row":"","gap-2":""},V={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},E={"w-full":"",flex:"","flex-row":"","gap-4":""},Q={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},S={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},N=x({__name:"emotions",setup(B){const l=u(""),p=u([]),r=u([]),d=u(!1),g=w({handlers:[async a=>{r.value.push(a.data)}]}),c=_(g);function v(){d.value=!0;const a=l.value.split("");for(const o of a)c.add(o);c.add(k),l.value="",d.value=!1}return(a,o)=>(t(),s("div",y,[e("div",M,[z(h(b),{modelValue:l.value,"onUpdate:modelValue":o[0]||(o[0]=n=>l.value=n),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:v},null,8,["modelValue"]),e("button",V,i(d.value?"Processing...":"Send"),1)]),e("div",E,[e("div",Q,[o[1]||(o[1]=e("h3",{"font-semibold":""}," Messages ",-1)),(t(!0),s(f,null,m(p.value,n=>(t(),s("div",{key:n},[e("div",null,i(n),1)]))),128))]),e("div",S,[o[2]||(o[2]=e("h3",{"font-semibold":""}," Emotions ",-1)),(t(!0),s(f,null,m(r.value,n=>(t(),s("div",{key:n},[e("div",null,i(n),1)]))),128))])])]))}});export{N as default}; diff --git a/assets/filter-message-Q-pfq8ka.js b/assets/filter-message-BeLJKrV5.js similarity index 95% rename from assets/filter-message-Q-pfq8ka.js rename to assets/filter-message-BeLJKrV5.js index 2aed49d16b94ac43252d786d12565c258dada750..cbe9b3f8585ef14302739cedd9b1cc7d15504250 100644 --- a/assets/filter-message-Q-pfq8ka.js +++ b/assets/filter-message-BeLJKrV5.js @@ -1 +1 @@ -import{d as g,g as u,r as m,c as v,o as _,a as s,b as x,D as d}from"./index-rD0Uu1v9.js";const b={flex:"","flex-col":"","gap-2":"","p-2":""},S={flex:"","flex-row":"","gap-2":""},k={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},w={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},V=g({__name:"filter-message",setup(z){const o=u(""),c=u(!1),i=u({content:""});async function f(r){return new Promise(e=>setTimeout(e,r))}async function p(){c.value=!0;const r=o.value.split("");let e;(a=>{a.Literal="literal",a.Special="special"})(e||(e={}));let l="literal",t="";for(const a of r){await f(50);let n=l;a==="<"?n="special":a===">"&&(n="literal"),l==="literal"&&n==="special"&&(i.value.content+=t,t=""),l==="special"&&n==="literal"&&(t=""),l==="literal"&&n==="literal"&&(i.value.content+=a,t=""),l=n}t&&(i.value.content+=t),o.value="",c.value=!1}return(r,e)=>{const l=m("BasicTextarea");return _(),v("div",b,[s("div",S,[x(l,{modelValue:o.value,"onUpdate:modelValue":e[0]||(e[0]=t=>o.value=t),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:p},null,8,["modelValue"]),s("button",k,d(c.value?"Processing...":"Send"),1)]),s("div",w,[e[1]||(e[1]=s("h3",{"font-semibold":""}," Streaming Message ",-1)),s("div",null,d(i.value.content),1)])])}}});export{V as default}; +import{d as g,g as u,r as m,c as v,o as _,a as s,b as x,D as d}from"./index-Dlp4W1Zl.js";const b={flex:"","flex-col":"","gap-2":"","p-2":""},S={flex:"","flex-row":"","gap-2":""},k={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},w={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},V=g({__name:"filter-message",setup(z){const o=u(""),c=u(!1),i=u({content:""});async function f(r){return new Promise(e=>setTimeout(e,r))}async function p(){c.value=!0;const r=o.value.split("");let e;(a=>{a.Literal="literal",a.Special="special"})(e||(e={}));let l="literal",t="";for(const a of r){await f(50);let n=l;a==="<"?n="special":a===">"&&(n="literal"),l==="literal"&&n==="special"&&(i.value.content+=t,t=""),l==="special"&&n==="literal"&&(t=""),l==="literal"&&n==="literal"&&(i.value.content+=a,t=""),l=n}t&&(i.value.content+=t),o.value="",c.value=!1}return(r,e)=>{const l=m("BasicTextarea");return _(),v("div",b,[s("div",S,[x(l,{modelValue:o.value,"onUpdate:modelValue":e[0]||(e[0]=t=>o.value=t),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:p},null,8,["modelValue"]),s("button",k,d(c.value?"Processing...":"Send"),1)]),s("div",w,[e[1]||(e[1]=s("h3",{"font-semibold":""}," Streaming Message ",-1)),s("div",null,d(i.value.content),1)])])}}});export{V as default}; diff --git a/assets/fireworks-ai-DLDw3hxW.js b/assets/fireworks-ai-BpaEuc1J.js similarity index 67% rename from assets/fireworks-ai-DLDw3hxW.js rename to assets/fireworks-ai-BpaEuc1J.js index efb749e066914588f787bc908bedb3b9805ca68a..150a320cd1523d41584361de4abf54e414f2220b 100644 --- a/assets/fireworks-ai-DLDw3hxW.js +++ b/assets/fireworks-ai-BpaEuc1J.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as k,i as w,bE as U,s as V,h as v,m as y,w as $,x as K,o as h,y as p,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as x}from"./providers-Dg3FpvfZ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="fireworks-ai",H=k({__name:"fireworks-ai",setup(B){const{t:d}=w(),_=U(),m=x(),{providers:o}=V(m),n=v(()=>m.getProviderMetadata(a)),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});y(()=>{var e,i;m.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),$([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return h(),K(t(S),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(P),null,{default:p(()=>[l(t(R),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=g=>r.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"fw-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=u=>s.value=u),placeholder:"https://api.fireworks.ai/inference/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as k,i as w,bE as U,s as V,h as v,m as y,w as $,x as K,o as h,y as p,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as x}from"./providers-BRCa7xUS.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="fireworks-ai",H=k({__name:"fireworks-ai",setup(B){const{t:d}=w(),_=U(),m=x(),{providers:o}=V(m),n=v(()=>m.getProviderMetadata(a)),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});y(()=>{var e,i;m.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),$([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return h(),K(t(S),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(P),null,{default:p(()=>[l(t(R),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=g=>r.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"fw-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=u=>s.value=u),placeholder:"https://api.fireworks.ai/inference/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; diff --git a/assets/image-B7AzUr5g.js b/assets/image-CD6Zjbv1.js similarity index 95% rename from assets/image-B7AzUr5g.js rename to assets/image-CD6Zjbv1.js index a2c336ead1237339a4b6c309bfb8542f5390fdc9..b27c1d23407859bc7851edd07fc4564e2b7a09b5 100644 --- a/assets/image-B7AzUr5g.js +++ b/assets/image-CD6Zjbv1.js @@ -1,2 +1,2 @@ -import{d as _,g as c,bD as y,c as d,o as u,a,C as x,D as b,e as v,bn as w}from"./index-rD0Uu1v9.js";const C={bg:"neutral-100",flex:"~ col","items-center":"","justify-center":"","rounded-lg":"","px-4":"","py-3":""},h={key:0},D=["src"],U={bg:"neutral-100",class:"text-wrap-any","max-h":"100","overflow-scroll":"","rounded-lg":"","text-wrap":"","text-black":"","font-mono":""},R=_({__name:"image",setup(k){const p=c(),n=c(""),{copy:g}=y({source:n});async function m(r){return new Promise((e,o)=>{const t=new FileReader;t.onload=s=>{var l,i;e(((i=(l=s.target)==null?void 0:l.result)==null?void 0:i.toString())||"")},t.onerror=s=>{o(s)},t.readAsDataURL(r)})}async function f(r){var t;const o=(t=r.target.files)==null?void 0:t[0];if(o){p.value=o;const s=await m(o);n.value=s}}return(r,e)=>(u(),d("div",null,[a("label",C,[a("input",{type:"file",accept:"image/*",hidden:"",onChange:f},null,32),e[1]||(e[1]=a("span",null,"Upload Image",-1))]),n.value?(u(),d("div",h,[a("img",{src:n.value,alt:"Uploaded Image","w-100":""},null,8,D),a("pre",U," "+b(n.value)+` +import{d as _,g as c,bD as y,c as d,o as u,a,C as x,D as b,e as v,bn as w}from"./index-Dlp4W1Zl.js";const C={bg:"neutral-100",flex:"~ col","items-center":"","justify-center":"","rounded-lg":"","px-4":"","py-3":""},h={key:0},D=["src"],U={bg:"neutral-100",class:"text-wrap-any","max-h":"100","overflow-scroll":"","rounded-lg":"","text-wrap":"","text-black":"","font-mono":""},R=_({__name:"image",setup(k){const p=c(),n=c(""),{copy:g}=y({source:n});async function m(r){return new Promise((e,o)=>{const t=new FileReader;t.onload=s=>{var l,i;e(((i=(l=s.target)==null?void 0:l.result)==null?void 0:i.toString())||"")},t.onerror=s=>{o(s)},t.readAsDataURL(r)})}async function f(r){var t;const o=(t=r.target.files)==null?void 0:t[0];if(o){p.value=o;const s=await m(o);n.value=s}}return(r,e)=>(u(),d("div",null,[a("label",C,[a("input",{type:"file",accept:"image/*",hidden:"",onChange:f},null,32),e[1]||(e[1]=a("span",null,"Upload Image",-1))]),n.value?(u(),d("div",h,[a("img",{src:n.value,alt:"Uploaded Image","w-100":""},null,8,D),a("pre",U," "+b(n.value)+` `,1),a("button",{bg:"primary-500",text:"white","mt-4":"","rounded-lg":"","px-4":"","py-2":"",onClick:e[0]||(e[0]=()=>v(g)())}," Copy Data URL ")])):x("",!0)]))}}),B=w(R,[["__scopeId","data-v-7edd53e6"]]);export{B as default}; diff --git a/assets/index-d-t5NO1c.js b/assets/index-CTgzm8SA.js similarity index 86% rename from assets/index-d-t5NO1c.js rename to assets/index-CTgzm8SA.js index 8b69bab3776dfec30008b94d22ba70ce08905d5d..26e679cae552ef52a0f4da78bb021520777bd2fd 100644 --- a/assets/index-d-t5NO1c.js +++ b/assets/index-CTgzm8SA.js @@ -1 +1 @@ -import{_ as w}from"./IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js";import"./live2d-zip-loader-BdiFCiUD.js";import{d as S,i as h,bE as z,s as A,v as C,bw as D,c as s,o as n,A as l,a as o,x as d,C as u,e,D as m,bx as p,by as B}from"./index-rD0Uu1v9.js";import{u as N}from"./providers-Dg3FpvfZ.js";import{I as P}from"./IconStatusItem-BolEMtws.js";import{u as $}from"./useIconAnimation-BDdHp70p.js";import{b as f}from"./route-block-B_A1xBdJ.js";const E={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},R={relative:""},T={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},V={text:"neutral-300 dark:neutral-500","text-nowrap":""},F={"text-nowrap":"","text-3xl":"","font-semibold":""},L={grid:"~ cols-2 gap-4"},M={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},j=S({__name:"index",setup(q){const{t:a}=h(),x=z(),_=N(),{allProvidersMetadata:g}=A(_),v=C(),{iconAnimationStarted:y,showIconAnimation:b,animationIcon:k}=$("i-lucide:brain");return(G,i)=>{const I=w,r=D("motion");return n(),s(p,null,[l((n(),s("div",E,[o("button",{onClick:i[0]||(i[0]=t=>e(x).back())},i[1]||(i[1]=[o("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),o("h1",R,[o("div",T,[o("span",V,m(e(a)("settings.title")),1)]),o("div",F,m(e(a)("settings.pages.providers.title")),1)])])),[[r]]),o("div",L,[(n(!0),s(p,null,B(e(g),(t,c)=>l((n(),d(e(P),{key:t.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+c*10,delay:c*50,title:t.localizedName,description:t.localizedDescription,icon:t.icon,"icon-color":t.iconColor,"icon-image":t.iconImage,to:`/settings/providers/${t.id}`,configured:t.configured},null,8,["duration","delay","title","description","icon","icon-color","icon-image","to","configured"])),[[r]])),128))]),e(b)?(n(),d(I,{key:0,"z-index":-1,icon:e(k),"icon-size":12,duration:1e3,started:e(y),"is-reverse":!0,position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)","text-color":"text-neutral-200/50 dark:text-neutral-600/20"},null,8,["icon","started"])):u("",!0),e(v).usePageSpecificTransitions?u("",!0):(n(),s("div",M,i[2]||(i[2]=[o("div",{text:"40","i-lucide:brain":""},null,-1)])))],64)}}});typeof f=="function"&&f(j);export{j as default}; +import{_ as w}from"./IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js";import"./live2d-zip-loader-C5j9stxV.js";import{d as S,i as h,bE as z,s as A,v as C,bw as D,c as s,o as n,A as l,a as o,x as d,C as u,e,D as m,bx as p,by as B}from"./index-Dlp4W1Zl.js";import{u as N}from"./providers-BRCa7xUS.js";import{I as P}from"./IconStatusItem-BxiCMDHT.js";import{u as $}from"./useIconAnimation-DMJpspm5.js";import{b as f}from"./route-block-B_A1xBdJ.js";const E={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},R={relative:""},T={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},V={text:"neutral-300 dark:neutral-500","text-nowrap":""},F={"text-nowrap":"","text-3xl":"","font-semibold":""},L={grid:"~ cols-2 gap-4"},M={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},j=S({__name:"index",setup(q){const{t:a}=h(),x=z(),_=N(),{allProvidersMetadata:g}=A(_),v=C(),{iconAnimationStarted:y,showIconAnimation:b,animationIcon:k}=$("i-lucide:brain");return(G,i)=>{const I=w,r=D("motion");return n(),s(p,null,[l((n(),s("div",E,[o("button",{onClick:i[0]||(i[0]=t=>e(x).back())},i[1]||(i[1]=[o("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),o("h1",R,[o("div",T,[o("span",V,m(e(a)("settings.title")),1)]),o("div",F,m(e(a)("settings.pages.providers.title")),1)])])),[[r]]),o("div",L,[(n(!0),s(p,null,B(e(g),(t,c)=>l((n(),d(e(P),{key:t.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+c*10,delay:c*50,title:t.localizedName,description:t.localizedDescription,icon:t.icon,"icon-color":t.iconColor,"icon-image":t.iconImage,to:`/settings/providers/${t.id}`,configured:t.configured},null,8,["duration","delay","title","description","icon","icon-color","icon-image","to","configured"])),[[r]])),128))]),e(b)?(n(),d(I,{key:0,"z-index":-1,icon:e(k),"icon-size":12,duration:1e3,started:e(y),"is-reverse":!0,position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)","text-color":"text-neutral-200/50 dark:text-neutral-600/20"},null,8,["icon","started"])):u("",!0),e(v).usePageSpecificTransitions?u("",!0):(n(),s("div",M,i[2]||(i[2]=[o("div",{text:"40","i-lucide:brain":""},null,-1)])))],64)}}});typeof f=="function"&&f(j);export{j as default}; diff --git a/assets/index-zxlyBIy_.js b/assets/index-CWukm1n3.js similarity index 92% rename from assets/index-zxlyBIy_.js rename to assets/index-CWukm1n3.js index 247f3481f6304686eda8474c445da56ef131e5e5..6bf1700ced2178231cced19143318acccd36f80d 100644 --- a/assets/index-zxlyBIy_.js +++ b/assets/index-CWukm1n3.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as k,bE as b,i as I,v as w,h as C,bw as S,c as r,o as n,A as d,a as i,x as l,C as m,e as s,D as g,bx as u,by as A}from"./index-rD0Uu1v9.js";import{I as B}from"./IconStatusItem-BolEMtws.js";import{_ as D}from"./IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js";import{u as z}from"./useIconAnimation-BDdHp70p.js";import{b as p}from"./route-block-B_A1xBdJ.js";const E={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},L={relative:""},N={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},V={text:"neutral-300 dark:neutral-500","text-nowrap":""},$={"text-nowrap":"","text-3xl":"","font-semibold":""},F={grid:"~ cols-1 sm:cols-2 gap-4"},P={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},R=k({__name:"index",setup(T){const f=b(),{t:e}=I(),y=w(),x=C(()=>[{id:"consciousness",name:e("settings.pages.modules.consciousness.title"),description:e("settings.pages.modules.consciousness.description"),icon:"i-lucide:ghost",to:"/settings/modules/consciousness",configured:!1},{id:"speech",name:e("settings.pages.modules.speech.title"),description:e("settings.pages.modules.speech.description"),icon:"i-lucide:mic",to:"/settings/modules/speech",configured:!1},{id:"hearing",name:e("settings.pages.modules.hearing.title"),description:e("settings.pages.modules.hearing.description"),icon:"i-lucide:ear",to:"",configured:!1},{id:"vision",name:e("settings.pages.modules.vision.title"),description:e("settings.pages.modules.vision.description"),icon:"i-lucide:eye",to:"",configured:!1},{id:"memory-short-term",name:e("settings.pages.modules.memory-short-term.title"),description:e("settings.pages.modules.memory-short-term.description"),icon:"i-lucide:book",to:"/settings/modules/memory-short-term",configured:!1},{id:"memory-long-term",name:e("settings.pages.modules.memory-long-term.title"),description:e("settings.pages.modules.memory-long-term.description"),icon:"i-lucide:book-copy",to:"/settings/modules/memory-long-term",configured:!1},{id:"messaging-discord",name:e("settings.pages.modules.messaging-discord.title"),description:e("settings.pages.modules.messaging-discord.description"),icon:"i-simple-icons:discord",to:"",configured:!1},{id:"x",name:e("settings.pages.modules.x.title"),description:e("settings.pages.modules.x.description"),icon:"i-simple-icons:x",to:"",configured:!1},{id:"game-minecraft",name:e("settings.pages.modules.gaming-minecraft.title"),description:e("settings.pages.modules.gaming-minecraft.description"),iconColor:"i-vscode-icons:file-type-minecraft",to:"",configured:!1},{id:"game-factorio",name:e("settings.pages.modules.gaming-factorio.title"),description:e("settings.pages.modules.gaming-factorio.description"),iconImage:"",to:"",configured:!1}]),{iconAnimationStarted:v,showIconAnimation:_,animationIcon:h}=z("i-lucide:blocks");return(j,o)=>{const a=S("motion");return n(),r(u,null,[d((n(),r("div",E,[i("button",{onClick:o[0]||(o[0]=t=>s(f).back())},o[1]||(o[1]=[i("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),i("h1",L,[i("div",N,[i("span",V,g(s(e)("settings.title")),1)]),i("div",$,g(s(e)("settings.pages.modules.title")),1)])])),[[a]]),i("div",F,[(n(!0),r(u,null,A(x.value,(t,c)=>d((n(),l(s(B),{key:t.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+c*10,delay:c*50,title:t.name,description:t.description,icon:t.icon,"icon-color":t.iconColor,"icon-image":t.iconImage,to:t.to,configured:t.configured},null,8,["duration","delay","title","description","icon","icon-color","icon-image","to","configured"])),[[a]])),128))]),s(_)?(n(),l(D,{key:0,icon:s(h),"icon-size":12,duration:1e3,started:s(v),"is-reverse":!0,"z-index":-1,"text-color":"text-neutral-200/50 dark:text-neutral-600/20",position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)"},null,8,["icon","started"])):m("",!0),s(y).usePageSpecificTransitions?m("",!0):(n(),r("div",P,o[2]||(o[2]=[i("div",{text:"40","i-lucide:blocks":""},null,-1)])))],64)}}});typeof p=="function"&&p(R);export{R as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as k,bE as b,i as I,v as w,h as C,bw as S,c as r,o as n,A as d,a as i,x as l,C as m,e as s,D as g,bx as u,by as A}from"./index-Dlp4W1Zl.js";import{I as B}from"./IconStatusItem-BxiCMDHT.js";import{_ as D}from"./IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js";import{u as z}from"./useIconAnimation-DMJpspm5.js";import{b as p}from"./route-block-B_A1xBdJ.js";const E={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},L={relative:""},N={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},V={text:"neutral-300 dark:neutral-500","text-nowrap":""},$={"text-nowrap":"","text-3xl":"","font-semibold":""},F={grid:"~ cols-1 sm:cols-2 gap-4"},P={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},R=k({__name:"index",setup(T){const f=b(),{t:e}=I(),y=w(),x=C(()=>[{id:"consciousness",name:e("settings.pages.modules.consciousness.title"),description:e("settings.pages.modules.consciousness.description"),icon:"i-lucide:ghost",to:"/settings/modules/consciousness",configured:!1},{id:"speech",name:e("settings.pages.modules.speech.title"),description:e("settings.pages.modules.speech.description"),icon:"i-lucide:mic",to:"/settings/modules/speech",configured:!1},{id:"hearing",name:e("settings.pages.modules.hearing.title"),description:e("settings.pages.modules.hearing.description"),icon:"i-lucide:ear",to:"",configured:!1},{id:"vision",name:e("settings.pages.modules.vision.title"),description:e("settings.pages.modules.vision.description"),icon:"i-lucide:eye",to:"",configured:!1},{id:"memory-short-term",name:e("settings.pages.modules.memory-short-term.title"),description:e("settings.pages.modules.memory-short-term.description"),icon:"i-lucide:book",to:"/settings/modules/memory-short-term",configured:!1},{id:"memory-long-term",name:e("settings.pages.modules.memory-long-term.title"),description:e("settings.pages.modules.memory-long-term.description"),icon:"i-lucide:book-copy",to:"/settings/modules/memory-long-term",configured:!1},{id:"messaging-discord",name:e("settings.pages.modules.messaging-discord.title"),description:e("settings.pages.modules.messaging-discord.description"),icon:"i-simple-icons:discord",to:"",configured:!1},{id:"x",name:e("settings.pages.modules.x.title"),description:e("settings.pages.modules.x.description"),icon:"i-simple-icons:x",to:"",configured:!1},{id:"game-minecraft",name:e("settings.pages.modules.gaming-minecraft.title"),description:e("settings.pages.modules.gaming-minecraft.description"),iconColor:"i-vscode-icons:file-type-minecraft",to:"",configured:!1},{id:"game-factorio",name:e("settings.pages.modules.gaming-factorio.title"),description:e("settings.pages.modules.gaming-factorio.description"),iconImage:"",to:"",configured:!1}]),{iconAnimationStarted:v,showIconAnimation:_,animationIcon:h}=z("i-lucide:blocks");return(j,o)=>{const a=S("motion");return n(),r(u,null,[d((n(),r("div",E,[i("button",{onClick:o[0]||(o[0]=t=>s(f).back())},o[1]||(o[1]=[i("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),i("h1",L,[i("div",N,[i("span",V,g(s(e)("settings.title")),1)]),i("div",$,g(s(e)("settings.pages.modules.title")),1)])])),[[a]]),i("div",F,[(n(!0),r(u,null,A(x.value,(t,c)=>d((n(),l(s(B),{key:t.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+c*10,delay:c*50,title:t.name,description:t.description,icon:t.icon,"icon-color":t.iconColor,"icon-image":t.iconImage,to:t.to,configured:t.configured},null,8,["duration","delay","title","description","icon","icon-color","icon-image","to","configured"])),[[a]])),128))]),s(_)?(n(),l(D,{key:0,icon:s(h),"icon-size":12,duration:1e3,started:s(v),"is-reverse":!0,"z-index":-1,"text-color":"text-neutral-200/50 dark:text-neutral-600/20",position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)"},null,8,["icon","started"])):m("",!0),s(y).usePageSpecificTransitions?m("",!0):(n(),r("div",P,o[2]||(o[2]=[i("div",{text:"40","i-lucide:blocks":""},null,-1)])))],64)}}});typeof p=="function"&&p(R);export{R as default}; diff --git a/assets/index-0FtS8e47.js b/assets/index-CgcZzzI2.js similarity index 59% rename from assets/index-0FtS8e47.js rename to assets/index-CgcZzzI2.js index bacaf5ccc5801a50b3455fb4fcd000679705eec6..774babe71934ce94e6d956bc4859bdf8a07e296d 100644 --- a/assets/index-0FtS8e47.js +++ b/assets/index-CgcZzzI2.js @@ -1,8 +1,8 @@ -var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Mi=(t,e,n)=>ka(t,typeof e!="symbol"?e+"":e,n);import{E as Aa,V as _a,a as Ea,c as Ma,r as Sa,b as Nr,d as Ia,e as Si,f as Ra,g as Ca,h as Na,s as La,i as Pa,j as Da}from"./live2d-zip-loader-BdiFCiUD.js";import{f as $n,g as W,h as Ue,i as Ot,t as Oa,d as Fe,j as Fa,k as za,l as Zr,w as je,m as pn,c as ie,o as ee,p as gn,q as Ba,s as Ze,v as Xt,x as Qt,y as Be,b as ke,a as F,z as at,A as _t,B as Jr,C as it,D as ge,e as H,M as yt,T as At,E as ei,F as Yn,G as Wo,Z as On,H as Ft,I as Ua,V as se,S as Ii,Q as Fn,O as $t,J as Pe,P as Et,K as ja,L as Xo,N as hn,U as ti,W as ze,X as Qo,Y as Zo,_ as ni,$ as yn,a0 as Va,a1 as ri,a2 as Ha,a3 as Jo,a4 as xt,a5 as ii,a6 as Mt,a7 as Ga,a8 as es,a9 as Dt,aa as ts,ab as $a,ac as Ya,ad as qa,ae as Ka,af as ns,ag as qn,ah as Wa,ai as Xa,aj as Qa,ak as Pt,al as Za,am as Ja,an as el,ao as tl,ap as er,aq as zn,ar as Lr,as as Nt,at as rs,au as Pr,av as Ht,aw as Ri,ax as Lt,ay as Gt,az as tr,aA as nl,aB as rl,aC as il,aD as ol,aE as is,aF as os,aG as Bn,aH as ss,aI as oi,aJ as Un,aK as as,aL as sl,n as Dr,aM as al,aN as Or,aO as ls,aP as ll,aQ as cn,aR as us,aS as ft,aT as vt,aU as mn,aV as ul,aW as cl,aX as fl,aY as dl,aZ as pl,a_ as si,a$ as hl,b0 as ml,b1 as gl,b2 as nr,b3 as yl,b4 as cs,b5 as xl,b6 as vl,b7 as bl,b8 as wl,b9 as Tl,ba as rr,bb as kl,bc as Al,bd as _l,be as Ci,bf as Ni,bg as Li,bh as Pi,bi as El,bj as Ml,bk as Sl,bl as Il,bm as Rl,bn as Kn,bo as Cl,bp as fs,bq as Nl,br as Ll,bs as Pl,bt as Dl,bu as ds,bv as jn,bw as ps,bx as ai,by as li,bz as Ol,bA as ir,bB as Fl,bC as zl}from"./index-rD0Uu1v9.js";import{s as Yt,c as Di,u as Bl,g as Ul}from"./speech-CUKri9wm.js";import{u as or}from"./queue-EbaGahVd.js";import{u as jl,a as Vl,b as Hl,l as Gl,_ as hs}from"./queues-kGVt0l-U.js";import{r as $l,a as Yl,b as ql,c as Kl,d as Wl,l as Xl,u as ui}from"./providers-Dg3FpvfZ.js";import{_ as Ql,a as Zl,r as on}from"./Model.vue_vue_type_script_setup_true_lang-DfGKadm0.js";import{_ as ci}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import{_ as Oi}from"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import{H as Jl}from"./HeaderLink-0aZMXKsY.js";import{u as ms}from"./consciousness-B-O47Lyx.js";import{d as Fi}from"./index-0_JGTbws.js";import{b as zi}from"./route-block-B_A1xBdJ.js";async function*eu(t,e){const n=t.getReader();try{for(;;){const{done:r,value:i}=await n.read();if(r)return;yield e(i)}}finally{n.releaseLock()}}function tu(t){const e=new Uint8Array(t.frequencyBinCount);t.getByteFrequencyData(e);const n=[];for(let i=0;i<700;i+=80)n.push(e[i]);return e.map(i=>i**1.2).map(i=>i*1.2).reduce((i,o)=>i+o,0)/e.length/100}function nu(t){const e=new Uint8Array(t.frequencyBinCount);t.getByteFrequencyData(e);const n=[];for(let u=0;u<700;u+=80)n.push(e[u]);const r=e.map(u=>u**1.5),i=Math.min(...r),s=Math.max(...r)-i;let a;return s===0?a=r.map(()=>0):a=r.map(u=>(u-i)/s),a.reduce((u,c)=>u+c,0)/e.length}function ru(t,e="linear"){switch(e){case"linear":return tu(t);case"minmax":return nu(t)}}const gs=$n("AudioContext",()=>({audioContext:new AudioContext,calculateVolume:ru})),iu=$n("SpeakingStore",()=>{const n=W(0),r=W(!1),i=Ue(()=>r.value?(30+70*n.value)/100:30);return{mouthOpenSize:n,nowSpeaking:r,nowSpeakingAvatarBorderOpacity:i}});function An(t,e,n){return e+n<0||e+n>=t.length-1?"":t[e+n]}function ou(t){let e="literal",n="";return{async consume(r){var i,o,s;for(let a=0;a"?(l+=An(r,a,1),u="literal",a++):l==="<"?u="special":l===">"&&(u="literal"),e==="literal"&&u==="special"?n!==""&&(await((i=t.onLiteral)==null?void 0:i.call(t,n)),n=""):e==="special"&&u==="literal"&&n!==""&&(n+=l,await((o=t.onSpecial)==null?void 0:o.call(t,n)),n=""),e==="literal"&&u==="literal"?(await((s=t.onLiteral)==null?void 0:s.call(t,l)),n=""):e==="special"&&u==="literal"?n="":n+=l,e=u}},async end(){var r,i;n!==""&&(e==="literal"?await((r=t.onLiteral)==null?void 0:r.call(t,n)):n.endsWith("|>")&&await((i=t.onSpecial)==null?void 0:i.call(t,n)))}}}function su(t,e){return{role:"system",content:[t,Aa.map(n=>`- ${n}`).join(` +var Ts=Object.defineProperty;var ks=(t,e,n)=>e in t?Ts(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Mi=(t,e,n)=>ks(t,typeof e!="symbol"?e+"":e,n);import{E as _s,V as As,a as Es,c as Ms,r as Ss,b as Nr,d as Is,e as Si,f as Rs,g as Cs,h as Ns,s as Ls,i as Ps,j as Ds}from"./live2d-zip-loader-C5j9stxV.js";import{f as $n,g as W,h as Ue,i as Ot,t as Os,d as ze,j as zs,k as Fs,l as Zr,w as je,m as pn,c as ie,o as ee,p as gn,q as Bs,s as Ze,v as Xt,x as Qt,y as Be,b as ke,a as z,z as st,A as At,B as Jr,C as it,D as ge,e as H,M as yt,T as _t,E as ei,F as qn,G as Wo,Z as On,H as zt,I as Us,V as ae,S as Ii,Q as zn,O as $t,J as Pe,P as Et,K as js,L as Xo,N as hn,U as ti,W as Fe,X as Qo,Y as Zo,_ as ni,$ as yn,a0 as Vs,a1 as ri,a2 as Hs,a3 as Jo,a4 as xt,a5 as ii,a6 as Mt,a7 as Gs,a8 as ea,a9 as Dt,aa as ta,ab as $s,ac as qs,ad as Ys,ae as Ks,af as na,ag as Yn,ah as Ws,ai as Xs,aj as Qs,ak as Pt,al as Zs,am as Js,an as el,ao as tl,ap as er,aq as Fn,ar as Lr,as as Nt,at as ra,au as Pr,av as Ht,aw as Ri,ax as Lt,ay as Gt,az as tr,aA as nl,aB as rl,aC as il,aD as ol,aE as ia,aF as oa,aG as Bn,aH as aa,aI as oi,aJ as Un,aK as sa,aL as al,n as Dr,aM as sl,aN as Or,aO as la,aP as ll,aQ as cn,aR as ua,aS as ft,aT as vt,aU as mn,aV as ul,aW as cl,aX as fl,aY as dl,aZ as pl,a_ as ai,a$ as hl,b0 as ml,b1 as gl,b2 as nr,b3 as yl,b4 as ca,b5 as xl,b6 as vl,b7 as bl,b8 as wl,b9 as Tl,ba as rr,bb as kl,bc as _l,bd as Al,be as Ci,bf as Ni,bg as Li,bh as Pi,bi as El,bj as Ml,bk as Sl,bl as Il,bm as Rl,bn as Kn,bo as Cl,bp as fa,bq as Nl,br as Ll,bs as Pl,bt as Dl,bu as da,bv as jn,bw as pa,bx as si,by as li,bz as Ol,bA as ir,bB as zl,bC as Fl}from"./index-Dlp4W1Zl.js";import{s as qt,c as Di,u as Bl,g as Ul}from"./speech-DU07zXBj.js";import{u as or}from"./queue-DW8o1RLT.js";import{u as jl,a as Vl,b as Hl,l as Gl,_ as ha}from"./queues-CJq1hDiQ.js";import{r as $l,a as ql,b as Yl,c as Kl,d as Wl,l as Xl,u as ui}from"./providers-BRCa7xUS.js";import{_ as Ql,a as Zl,r as on}from"./Model.vue_vue_type_script_setup_true_lang-CSqfK4Nz.js";import{_ as ci}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import{_ as Oi}from"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import{H as Jl}from"./HeaderLink-Dg_3MlXg.js";import{u as ma}from"./consciousness-CnU1Bi0O.js";import{d as zi}from"./index-YJa3XIzO.js";import{b as Fi}from"./route-block-B_A1xBdJ.js";async function*eu(t,e){const n=t.getReader();try{for(;;){const{done:r,value:i}=await n.read();if(r)return;yield e(i)}}finally{n.releaseLock()}}function tu(t){const e=new Uint8Array(t.frequencyBinCount);t.getByteFrequencyData(e);const n=[];for(let i=0;i<700;i+=80)n.push(e[i]);return e.map(i=>i**1.2).map(i=>i*1.2).reduce((i,o)=>i+o,0)/e.length/100}function nu(t){const e=new Uint8Array(t.frequencyBinCount);t.getByteFrequencyData(e);const n=[];for(let u=0;u<700;u+=80)n.push(e[u]);const r=e.map(u=>u**1.5),i=Math.min(...r),a=Math.max(...r)-i;let s;return a===0?s=r.map(()=>0):s=r.map(u=>(u-i)/a),s.reduce((u,c)=>u+c,0)/e.length}function ru(t,e="linear"){switch(e){case"linear":return tu(t);case"minmax":return nu(t)}}const ga=$n("AudioContext",()=>({audioContext:new AudioContext,calculateVolume:ru})),iu=$n("SpeakingStore",()=>{const n=W(0),r=W(!1),i=Ue(()=>r.value?(30+70*n.value)/100:30);return{mouthOpenSize:n,nowSpeaking:r,nowSpeakingAvatarBorderOpacity:i}});function _n(t,e,n){return e+n<0||e+n>=t.length-1?"":t[e+n]}function ou(t){let e="literal",n="";return{async consume(r){var i,o,a;for(let s=0;s"?(l+=_n(r,s,1),u="literal",s++):l==="<"?u="special":l===">"&&(u="literal"),e==="literal"&&u==="special"?n!==""&&(await((i=t.onLiteral)==null?void 0:i.call(t,n)),n=""):e==="special"&&u==="literal"&&n!==""&&(n+=l,await((o=t.onSpecial)==null?void 0:o.call(t,n)),n=""),e==="literal"&&u==="literal"?(await((a=t.onLiteral)==null?void 0:a.call(t,l)),n=""):e==="special"&&u==="literal"?n="":n+=l,e=u}},async end(){var r,i;n!==""&&(e==="literal"?await((r=t.onLiteral)==null?void 0:r.call(t,n)):n.endsWith("|>")&&await((i=t.onSpecial)==null?void 0:i.call(t,n)))}}}function au(t,e){return{role:"system",content:[t,_s.map(n=>`- ${n}`).join(` `),e].join(` -`)}}var au=async t=>{var e;return(t.fetch??globalThis.fetch)($l("chat/completions",t.baseURL),{body:ql({...t,tools:(e=t.tools)==null?void 0:e.map(n=>({function:Kl({...n.function,returns:void 0}),type:"function"}))}),headers:Yl({"Content-Type":"application/json",...t.headers},t.apiKey),method:"POST",signal:t.abortSignal}).then(Wl)},lu=({finishReason:t,maxSteps:e,stepsLength:n,toolCallsLength:r})=>{if(n===0)return"initial";if(n0&&t==="tool_calls")return"tool-result";if(!["error","length"].includes(t))return"continue"}return"done"},uu=t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>!!(typeof e=="object"&&"type"in e&&["audio","image","text"].includes(e.type)))?t:JSON.stringify(t),cu=async({abortSignal:t,messages:e,toolCall:n,tools:r})=>{const i=r==null?void 0:r.find(a=>a.function.name===n.function.name);if(!i){const a=r==null?void 0:r.map(u=>u.function.name),l=a==null||a.length===0?"No tools are available.":`Available tools: ${a.join(", ")}.`;throw new Error(`Model tried to call unavailable tool '${n.function.name}. ${l}.`)}const o=JSON.parse(n.function.arguments),s=uu(await i.execute(o,{abortSignal:t,messages:e,toolCallId:n.id}));return{parsedArgs:o,result:s,toolName:n.function.name}},sr=class extends Error{constructor(e,n){super(e);Mi(this,"response");this.name="XSAIError",this.response=n}},Bi="data:",fu=t=>{if(!t||!t.startsWith(Bi))return[void 0,!1];const e=t.slice(Bi.length),n=e.startsWith(" ")?e.slice(1):e;if(n==="[DONE]")return[void 0,!0];if(n.startsWith("{")&&n.includes('"error":'))throw new Error(`Error from server: ${n}`);return[JSON.parse(n),!1]},du=async t=>{let e,n,r;const i=new ReadableStream({start(p){e=p}}),o=new ReadableStream({start(p){n=p}}),s=new ReadableStream({start(p){r=p}}),a=t.maxSteps??1,l=new TextDecoder,u=[],c=async p=>{var I,_,C;const d={choices:[],finishReason:"error",messages:structuredClone(p.messages),stepType:"initial",toolCalls:[],toolResults:[]},b={};let x="",v=!0;const T=(P,h)=>{if(P.endedToolCallIDs.has(h))return;const M=d.choices[P.index].message.tool_calls[h];try{M.function.parsed_arguments=JSON.parse(M.function.arguments)}catch(y){P.toolCallErrors[h]=y}P.endedToolCallIDs.add(h),P.currentToolID=null};if(await au({...p,stream:!0}).then(async P=>P.body.pipeThrough(new TransformStream({transform:async(h,M)=>{const y=l.decode(h,{stream:!0});x+=y;const g=x.split(` -`);x=g.pop()??"";for(const m of g)try{const[k,E]=fu(m);if(E)break;k&&M.enqueue(k)}catch(k){M.error(k)}}})).pipeTo(new WritableStream({abort:h=>{e.error(h),n.error(h),r.error(h)},write:async h=>{var Q,A,te;(Q=p.onChunk)==null||Q.call(p,h),e.enqueue(h);const M=h.choices[0];if(!M)throw new sr("no choice found");M.delta.tool_calls&&(v=!1);const{delta:y,finish_reason:g,index:m,...k}=M,E=(A=d.choices)[m]??(A[m]={finish_reason:g,index:m,message:{role:"assistant"}});if(g!==void 0){if(d.finishReason=g,E.finish_reason=g,g==="length")throw new sr("length exceeded");if(g==="content_filter")throw new sr("content filter")}Object.assign(E,k);const{content:O,refusal:z,tool_calls:D,...B}=y,X=E.message;Object.assign(X,B),z!==void 0&&(X.refusal=(X.refusal||"")+z),O!==void 0&&(X.content=(X.content||"")+O,v&&(r==null||r.enqueue(O)));for(const{function:ce,id:R,type:pe}of D||[]){X.tool_calls??(X.tool_calls={});const ye=(te=X.tool_calls)[R]??(te[R]={function:{arguments:"",name:ce.name,parsed_arguments:{}},id:R,type:pe});ye.function.arguments+=ce.arguments}const Z=b[m]??(b[m]={calledToolCallIDs:new Set,currentToolID:null,endedToolCallIDs:new Set,index:m,toolCallErrors:{},toolCallResults:{}});g&&Z.currentToolID!==null&&T(Z,Z.currentToolID);for(const ce of y.tool_calls||[])Z.currentToolID!==null&&Z.currentToolID!==ce.id&&T(Z,Z.currentToolID),Z.calledToolCallIDs.add(ce.id),Z.currentToolID=ce.id}}))),d.messages.push({content:((I=d.choices[0])==null?void 0:I.message.content)??"",refusal:(_=d.choices[0])==null?void 0:_.message.refusal,role:"assistant"}),await Promise.allSettled(d.choices.map(async P=>{const h=b[P.index];return Promise.allSettled([...h.endedToolCallIDs].map(async M=>{const y=P.message.tool_calls[M];if(d.toolCalls.push({args:y.function.arguments,toolCallId:M,toolCallType:"function",toolName:y.function.name}),!h.toolCallResults[M])try{const{result:g}=await cu({abortSignal:p.abortSignal,messages:p.messages,toolCall:y,tools:p.tools});h.toolCallResults[M]=g,d.messages.push({content:g,role:"tool",tool_call_id:M}),d.toolResults.push({args:y.function.parsed_arguments,result:g,toolCallId:M,toolName:y.function.name})}catch(g){h.toolCallErrors[M]=g}}))})),d.stepType=lu({finishReason:d.finishReason,maxSteps:a,stepsLength:u.length,toolCallsLength:d.toolCalls.length}),u.push(d),n.enqueue(d),(C=p.onStepFinish)==null||C.call(p,d),!v)return async()=>c({...p,messages:d.messages})};return(async()=>{var d;let p=await c(t);for(;typeof p=="function"&&u.length{e.error(p),n.error(p),r.error(p)}),Promise.resolve({chunkStream:i,stepStream:o,textStream:s})};const pu=$n("llm",()=>{async function t(n,r,i,o){const s=o==null?void 0:o.headers;return await du({...r.chat(n),messages:i,streamOptions:{usage:!0},headers:s})}async function e(n,r){if(n==="")return[];try{return await Xl({baseURL:n.endsWith("/")?n:`${n}/`,apiKey:r})}catch(i){if(String(i).includes("Failed to construct 'URL': Invalid URL"))return[];throw i}}return{models:e,stream:t}}),St=$n("chat",()=>{const{stream:t}=pu(),{t:e}=Ot(),n=W(!1),r=W([]),i=W([]),o=W([]),s=W([]),a=W([]),l=W([]),u=W([]),c=W([]);function f(h){r.value.push(h)}function p(h){i.value.push(h)}function d(h){o.value.push(h)}function b(h){s.value.push(h)}function x(h){a.value.push(h)}function v(h){l.value.push(h)}function T(h){u.value.push(h)}function I(h){c.value.push(h)}const _=W([su(e("prompt.prefix"),e("prompt.suffix"))]),C=W({role:"assistant",content:""});async function P(h,M){var y;try{if(n.value=!0,!h)return;for(const D of r.value)await D(h);C.value={role:"assistant",content:""},_.value.push({role:"user",content:h}),_.value.push(C.value);const g=_.value.slice(0,_.value.length-1).map(D=>Oa(D));for(const D of i.value)await D(h);for(const D of o.value)await D(h);const m=(y=M.providerConfig)==null?void 0:y.headers,k=m==null?void 0:m.filter(D=>D.key&&D.value).reduce((D,B)=>(D[B.key]=B.value,D),{}),E=await t(M.model,M.chatProvider,g,{headers:k});for(const D of s.value)await D(h);let O="";const z=ou({onLiteral:async D=>{for(const B of a.value)await B(D);C.value.content+=D},onSpecial:async D=>{for(const B of l.value)await B(D)}});for await(const D of eu(E.textStream,async B=>B))O+=D,await z.consume(D);await z.end();for(const D of u.value)await D();for(const D of c.value)await D(O);console.debug("LLM output:",O)}finally{n.value=!1}}return{sending:n,messages:_,streamingMessage:C,send:P,onBeforeMessageComposed:f,onAfterMessageComposed:p,onBeforeSend:d,onAfterSend:b,onTokenLiteral:x,onTokenSpecial:v,onStreamEnd:T,onAssistantResponseEnd:I}}),ys=Fe({__name:"Screen",setup(t){const e=W(),n=Fa(Ba),{width:r,height:i}=za(),o=Zr(e,{immediate:!0,windowResize:!0,reset:!0}),s=Ue(()=>n.between("sm","md").value||n.smaller("sm").value),a=Ue(()=>n.between("md","lg").value),l=Ue(()=>n.greaterOrEqual("lg").value),u=Ue(()=>l.value?o.width.value:s.value||a.value?r.value-16:o.width.value),c=W(0);return je([r,i,e],()=>{var p,d;const f=(d=(p=e.value)==null?void 0:p.parentElement)==null?void 0:d.getBoundingClientRect();l.value||s.value||a.value?c.value=(f==null?void 0:f.height)||0:c.value=600}),je([o.width,o.height],()=>{l.value||s.value||a.value?c.value=o.height.value:c.value=600}),pn(async()=>{e.value&&o.update()}),(f,p)=>(ee(),ie("div",{ref_key:"containerRef",ref:e,"h-full":"","w-full":""},[gn(f.$slots,"default",{width:u.value,height:c.value})],512))}}),hu={absolute:"",bottom:"3",right:"3"},mu={flex:"~ row","cursor-pointer":""},gu=["checked","aria-checked"],yu={key:0,"min-w":"50vw",z:"(ee(),Qt(ys,{relative:""},{default:Be(({width:s,height:a})=>[ke(Zl,{width:s,height:a},{default:Be(({app:l})=>[ke(Ql,{app:l,"mouth-open-size":t.mouthOpenSize,width:s,height:a,paused:t.paused},null,8,["app","mouth-open-size","width","height","paused"])]),_:2},1032,["width","height"]),F("div",hu,[F("div",mu,[F("label",{class:at([n.value?"bg-zinc-300 dark:bg-zinc-200":"bg-zinc-100 dark:bg-zinc-700"]),transition:"all ease-in-out duration-500",text:"lg zinc-500 dark:zinc-400","m-1":"","h-fit":"","w-fit":"","cursor-pointer":"","appearance-none":"","gap-1":"","rounded-lg":"","rounded-md":"","border-none":"","p-2":"","outline-none":""},[_t(F("input",{"onUpdate:modelValue":o[0]||(o[0]=l=>n.value=l),checked:n.value,"aria-checked":n.value,name:"showLive2DViewerInspector",type:"checkbox",hidden:"","appearance-none":"","outline-none":""},null,8,gu),[[Jr,n.value]]),o[8]||(o[8]=F("div",{"select-none":""},[F("div",{"i-solar:bug-bold-duotone":""})],-1))],2)]),ke(ci,null,{default:Be(()=>[n.value?(ee(),ie("div",yu,[F("div",xu,[F("div",vu,[F("span",null,ge(H(e)("stage.viewers.debug-menu.emotions")),1)]),F("div",bu,[F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[1]||(o[1]=l=>r.value={group:"Surprise",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.surprised")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[2]||(o[2]=l=>r.value={group:"Sad",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.sad")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[3]||(o[3]=l=>r.value={group:"Angry",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.angry")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[4]||(o[4]=l=>r.value={group:"Happy",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.happy")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[5]||(o[5]=l=>r.value={group:"Awkward",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.awkward")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[6]||(o[6]=l=>r.value={group:"Question",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.question")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[7]||(o[7]=l=>r.value={group:"Think",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.think")),1)])])])):it("",!0)]),_:1})])]),_:1}))}});var Tu=Object.defineProperty,ku=(t,e,n)=>e in t?Tu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Au=(t,e,n)=>ku(t,e+"",n);function _u(t){return Wa()?(Xa(t),!0):!1}function xs(t){return typeof t=="function"?t():H(t)}const Eu=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Mu=Object.prototype.toString,Su=t=>Mu.call(t)==="[object Object]",Iu=()=>{},Ru=Eu?window:void 0;function Cu(t){var e;const n=xs(t);return(e=n==null?void 0:n.$el)!=null?e:n}function ar(...t){let e,n,r,i;if(typeof t[0]=="string"||Array.isArray(t[0])?([n,r,i]=t,e=Ru):[e,n,r,i]=t,!e)return Iu;Array.isArray(n)||(n=[n]),Array.isArray(r)||(r=[r]);const o=[],s=()=>{o.forEach(c=>c()),o.length=0},a=(c,f,p,d)=>(c.addEventListener(f,p,d),()=>c.removeEventListener(f,p,d)),l=je(()=>[Cu(e),xs(i)],([c,f])=>{if(s(),!c)return;const p=Su(f)?{...f}:f;o.push(...n.flatMap(d=>r.map(b=>a(c,d,b,p))))},{immediate:!0,flush:"post"}),u=()=>{l(),s()};return _u(u),u}function vs(t,e,n,r){const i=class extends yn{constructor(o={}){const s=Object.entries(t);super({uniforms:s.reduce((a,[l,u])=>{const c=ri.clone({[l]:{value:u}});return{...a,...c}},{}),vertexShader:e,fragmentShader:n}),Au(this,"key",""),s.forEach(([a])=>Object.defineProperty(this,a,{get:()=>this.uniforms[a].value,set:l=>this.uniforms[a].value=l})),Object.assign(this,o)}};return i.key=Dt.generateUUID(),i}vs({color:new ze("white"),scale:new Pe(1,1),imageBounds:new Pe(1,1),resolution:1024,map:null,zoom:1,radius:0,grayscale:0,opacity:1},` +`)}}var su=async t=>{var e;return(t.fetch??globalThis.fetch)($l("chat/completions",t.baseURL),{body:Yl({...t,tools:(e=t.tools)==null?void 0:e.map(n=>({function:Kl({...n.function,returns:void 0}),type:"function"}))}),headers:ql({"Content-Type":"application/json",...t.headers},t.apiKey),method:"POST",signal:t.abortSignal}).then(Wl)},lu=({finishReason:t,maxSteps:e,stepsLength:n,toolCallsLength:r})=>{if(n===0)return"initial";if(n0&&t==="tool_calls")return"tool-result";if(!["error","length"].includes(t))return"continue"}return"done"},uu=t=>typeof t=="string"||Array.isArray(t)&&t.every(e=>!!(typeof e=="object"&&"type"in e&&["audio","image","text"].includes(e.type)))?t:JSON.stringify(t),cu=async({abortSignal:t,messages:e,toolCall:n,tools:r})=>{const i=r==null?void 0:r.find(s=>s.function.name===n.function.name);if(!i){const s=r==null?void 0:r.map(u=>u.function.name),l=s==null||s.length===0?"No tools are available.":`Available tools: ${s.join(", ")}.`;throw new Error(`Model tried to call unavailable tool '${n.function.name}. ${l}.`)}const o=JSON.parse(n.function.arguments),a=uu(await i.execute(o,{abortSignal:t,messages:e,toolCallId:n.id}));return{parsedArgs:o,result:a,toolName:n.function.name}},ar=class extends Error{constructor(e,n){super(e);Mi(this,"response");this.name="XSAIError",this.response=n}},Bi="data:",fu=t=>{if(!t||!t.startsWith(Bi))return[void 0,!1];const e=t.slice(Bi.length),n=e.startsWith(" ")?e.slice(1):e;if(n==="[DONE]")return[void 0,!0];if(n.startsWith("{")&&n.includes('"error":'))throw new Error(`Error from server: ${n}`);return[JSON.parse(n),!1]},du=async t=>{let e,n,r;const i=new ReadableStream({start(p){e=p}}),o=new ReadableStream({start(p){n=p}}),a=new ReadableStream({start(p){r=p}}),s=t.maxSteps??1,l=new TextDecoder,u=[],c=async p=>{var I,A,C;const d={choices:[],finishReason:"error",messages:structuredClone(p.messages),stepType:"initial",toolCalls:[],toolResults:[]},b={};let x="",v=!0;const T=(P,h)=>{P.endedToolCallIDs.has(h)||(P.endedToolCallIDs.add(h),P.currentToolID=null)};if(await su({...p,stream:!0}).then(async P=>P.body.pipeThrough(new TransformStream({transform:async(h,S)=>{const y=l.decode(h,{stream:!0});x+=y;const g=x.split(` +`);x=g.pop()??"";for(const m of g)try{const[k,E]=fu(m);if(E)break;k&&S.enqueue(k)}catch(k){S.error(k)}}})).pipeTo(new WritableStream({abort:h=>{e.error(h),n.error(h),r.error(h)},write:async h=>{var Q,_,te;(Q=p.onChunk)==null||Q.call(p,h),e.enqueue(h);const S=h.choices[0];if(!S)throw new ar("no choice found");S.delta.tool_calls&&(v=!1);const{delta:y,finish_reason:g,index:m,...k}=S,E=(_=d.choices)[m]??(_[m]={finish_reason:g,index:m,message:{role:"assistant"}});if(g!==void 0){if(d.finishReason=g,E.finish_reason=g,g==="length")throw new ar("length exceeded");if(g==="content_filter")throw new ar("content filter")}Object.assign(E,k);const{content:O,refusal:F,tool_calls:D,...B}=y,X=E.message;Object.assign(X,B),F!==void 0&&(X.refusal=(X.refusal||"")+F),O!==void 0&&(X.content=(X.content||"")+O,v&&(r==null||r.enqueue(O)));for(const{function:ce,id:R,type:pe}of D||[]){X.tool_calls??(X.tool_calls={});const ye=(te=X.tool_calls)[R]??(te[R]={function:{arguments:"",name:ce.name,parsed_arguments:{}},id:R,type:pe});ye.function.arguments+=ce.arguments}const Z=b[m]??(b[m]={calledToolCallIDs:new Set,currentToolID:null,endedToolCallIDs:new Set,index:m,toolCallErrors:{},toolCallResults:{}});g&&Z.currentToolID!==null&&T(Z,Z.currentToolID);for(const ce of y.tool_calls||[])Z.currentToolID!==null&&Z.currentToolID!==ce.id&&T(Z,Z.currentToolID),Z.calledToolCallIDs.add(ce.id),Z.currentToolID=ce.id}}))),d.messages.push({content:((I=d.choices[0])==null?void 0:I.message.content)??"",refusal:(A=d.choices[0])==null?void 0:A.message.refusal,role:"assistant"}),await Promise.allSettled(d.choices.map(async P=>{const h=b[P.index];return Promise.allSettled([...h.endedToolCallIDs].map(async S=>{const y=P.message.tool_calls[S];if(d.toolCalls.push({args:y.function.arguments,toolCallId:S,toolCallType:"function",toolName:y.function.name}),!h.toolCallResults[S])try{const{parsedArgs:g,result:m,toolName:k}=await cu({abortSignal:p.abortSignal,messages:p.messages,toolCall:y,tools:p.tools});y.function.parsed_arguments=g,h.toolCallResults[S]=m,d.messages.push({content:m,role:"tool",tool_call_id:S}),d.toolResults.push({args:g,result:m,toolCallId:S,toolName:k})}catch(g){h.toolCallErrors[S]=g}}))})),d.stepType=lu({finishReason:d.finishReason,maxSteps:s,stepsLength:u.length,toolCallsLength:d.toolCalls.length}),u.push(d),n.enqueue(d),(C=p.onStepFinish)==null||C.call(p,d),!v)return async()=>c({...p,messages:d.messages})};return(async()=>{var d;let p=await c(t);for(;typeof p=="function"&&u.length{e.error(p),n.error(p),r.error(p)}),Promise.resolve({chunkStream:i,stepStream:o,textStream:a})};const pu=$n("llm",()=>{async function t(n,r,i,o){const a=o==null?void 0:o.headers;return await du({...r.chat(n),messages:i,streamOptions:{usage:!0},headers:a})}async function e(n,r){if(n==="")return[];try{return await Xl({baseURL:n.endsWith("/")?n:`${n}/`,apiKey:r})}catch(i){if(String(i).includes("Failed to construct 'URL': Invalid URL"))return[];throw i}}return{models:e,stream:t}}),St=$n("chat",()=>{const{stream:t}=pu(),{t:e}=Ot(),n=W(!1),r=W([]),i=W([]),o=W([]),a=W([]),s=W([]),l=W([]),u=W([]),c=W([]);function f(h){r.value.push(h)}function p(h){i.value.push(h)}function d(h){o.value.push(h)}function b(h){a.value.push(h)}function x(h){s.value.push(h)}function v(h){l.value.push(h)}function T(h){u.value.push(h)}function I(h){c.value.push(h)}const A=W([au(e("prompt.prefix"),e("prompt.suffix"))]),C=W({role:"assistant",content:""});async function P(h,S){var y;try{if(n.value=!0,!h)return;for(const D of r.value)await D(h);C.value={role:"assistant",content:""},A.value.push({role:"user",content:h}),A.value.push(C.value);const g=A.value.slice(0,A.value.length-1).map(D=>Os(D));for(const D of i.value)await D(h);for(const D of o.value)await D(h);const m=(y=S.providerConfig)==null?void 0:y.headers,k=m==null?void 0:m.filter(D=>D.key&&D.value).reduce((D,B)=>(D[B.key]=B.value,D),{}),E=await t(S.model,S.chatProvider,g,{headers:k});for(const D of a.value)await D(h);let O="";const F=ou({onLiteral:async D=>{for(const B of s.value)await B(D);C.value.content+=D},onSpecial:async D=>{for(const B of l.value)await B(D)}});for await(const D of eu(E.textStream,async B=>B))O+=D,await F.consume(D);await F.end();for(const D of u.value)await D();for(const D of c.value)await D(O);console.debug("LLM output:",O)}finally{n.value=!1}}return{sending:n,messages:A,streamingMessage:C,send:P,onBeforeMessageComposed:f,onAfterMessageComposed:p,onBeforeSend:d,onAfterSend:b,onTokenLiteral:x,onTokenSpecial:v,onStreamEnd:T,onAssistantResponseEnd:I}}),ya=ze({__name:"Screen",setup(t){const e=W(),n=zs(Bs),{width:r,height:i}=Fs(),o=Zr(e,{immediate:!0,windowResize:!0,reset:!0}),a=Ue(()=>n.between("sm","md").value||n.smaller("sm").value),s=Ue(()=>n.between("md","lg").value),l=Ue(()=>n.greaterOrEqual("lg").value),u=Ue(()=>l.value?o.width.value:a.value||s.value?r.value-16:o.width.value),c=W(0);return je([r,i,e],()=>{var p,d;const f=(d=(p=e.value)==null?void 0:p.parentElement)==null?void 0:d.getBoundingClientRect();l.value||a.value||s.value?c.value=(f==null?void 0:f.height)||0:c.value=600}),je([o.width,o.height],()=>{l.value||a.value||s.value?c.value=o.height.value:c.value=600}),pn(async()=>{e.value&&o.update()}),(f,p)=>(ee(),ie("div",{ref_key:"containerRef",ref:e,"h-full":"","w-full":""},[gn(f.$slots,"default",{width:u.value,height:c.value})],512))}}),hu={absolute:"",bottom:"3",right:"3"},mu={flex:"~ row","cursor-pointer":""},gu=["checked","aria-checked"],yu={key:0,"min-w":"50vw",z:"(ee(),Qt(ya,{relative:""},{default:Be(({width:a,height:s})=>[ke(Zl,{width:a,height:s},{default:Be(({app:l})=>[ke(Ql,{app:l,"mouth-open-size":t.mouthOpenSize,width:a,height:s,paused:t.paused},null,8,["app","mouth-open-size","width","height","paused"])]),_:2},1032,["width","height"]),z("div",hu,[z("div",mu,[z("label",{class:st([n.value?"bg-zinc-300 dark:bg-zinc-200":"bg-zinc-100 dark:bg-zinc-700"]),transition:"all ease-in-out duration-500",text:"lg zinc-500 dark:zinc-400","m-1":"","h-fit":"","w-fit":"","cursor-pointer":"","appearance-none":"","gap-1":"","rounded-lg":"","rounded-md":"","border-none":"","p-2":"","outline-none":""},[At(z("input",{"onUpdate:modelValue":o[0]||(o[0]=l=>n.value=l),checked:n.value,"aria-checked":n.value,name:"showLive2DViewerInspector",type:"checkbox",hidden:"","appearance-none":"","outline-none":""},null,8,gu),[[Jr,n.value]]),o[8]||(o[8]=z("div",{"select-none":""},[z("div",{"i-solar:bug-bold-duotone":""})],-1))],2)]),ke(ci,null,{default:Be(()=>[n.value?(ee(),ie("div",yu,[z("div",xu,[z("div",vu,[z("span",null,ge(H(e)("stage.viewers.debug-menu.emotions")),1)]),z("div",bu,[z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[1]||(o[1]=l=>r.value={group:"Surprise",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.surprised")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[2]||(o[2]=l=>r.value={group:"Sad",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.sad")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[3]||(o[3]=l=>r.value={group:"Angry",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.angry")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[4]||(o[4]=l=>r.value={group:"Happy",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.happy")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[5]||(o[5]=l=>r.value={group:"Awkward",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.awkward")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[6]||(o[6]=l=>r.value={group:"Question",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.question")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[7]||(o[7]=l=>r.value={group:"Think",index:0})},ge(H(e)("stage.viewers.debug-menu.emotions-btn.think")),1)])])])):it("",!0)]),_:1})])]),_:1}))}});var Tu=Object.defineProperty,ku=(t,e,n)=>e in t?Tu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_u=(t,e,n)=>ku(t,e+"",n);function Au(t){return Ws()?(Xs(t),!0):!1}function xa(t){return typeof t=="function"?t():H(t)}const Eu=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Mu=Object.prototype.toString,Su=t=>Mu.call(t)==="[object Object]",Iu=()=>{},Ru=Eu?window:void 0;function Cu(t){var e;const n=xa(t);return(e=n==null?void 0:n.$el)!=null?e:n}function sr(...t){let e,n,r,i;if(typeof t[0]=="string"||Array.isArray(t[0])?([n,r,i]=t,e=Ru):[e,n,r,i]=t,!e)return Iu;Array.isArray(n)||(n=[n]),Array.isArray(r)||(r=[r]);const o=[],a=()=>{o.forEach(c=>c()),o.length=0},s=(c,f,p,d)=>(c.addEventListener(f,p,d),()=>c.removeEventListener(f,p,d)),l=je(()=>[Cu(e),xa(i)],([c,f])=>{if(a(),!c)return;const p=Su(f)?{...f}:f;o.push(...n.flatMap(d=>r.map(b=>s(c,d,b,p))))},{immediate:!0,flush:"post"}),u=()=>{l(),a()};return Au(u),u}function va(t,e,n,r){const i=class extends yn{constructor(o={}){const a=Object.entries(t);super({uniforms:a.reduce((s,[l,u])=>{const c=ri.clone({[l]:{value:u}});return{...s,...c}},{}),vertexShader:e,fragmentShader:n}),_u(this,"key",""),a.forEach(([s])=>Object.defineProperty(this,s,{get:()=>this.uniforms[s].value,set:l=>this.uniforms[s].value=l})),Object.assign(this,o)}};return i.key=Dt.generateUUID(),i}va({color:new Fe("white"),scale:new Pe(1,1),imageBounds:new Pe(1,1),resolution:1024,map:null,zoom:1,radius:0,grayscale:0,opacity:1},` varying vec2 vUv; varying vec2 vPos; void main() { @@ -57,7 +57,7 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config #include #include } - `);const fi=parseInt(Qa.replace(/\D+/g,""));var Nu=Object.defineProperty,Lu=(t,e,n)=>e in t?Nu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pu=(t,e,n)=>(Lu(t,e+"",n),n);async function Ui(t){const e=await t.arrayBuffer(),n=btoa(String.fromCharCode(...new Uint8Array(e)));return`data:${t.type||""};base64,${n}`}let _n,lr,Bt,En;function ur(t,e=1/0,n=null){lr||(lr=new ts(2,2,1,1)),Bt||(Bt=new yn({uniforms:{blitTexture:new il(t)},vertexShader:` + `);const fi=parseInt(Qs.replace(/\D+/g,""));var Nu=Object.defineProperty,Lu=(t,e,n)=>e in t?Nu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pu=(t,e,n)=>(Lu(t,e+"",n),n);async function Ui(t){const e=await t.arrayBuffer(),n=btoa(String.fromCharCode(...new Uint8Array(e)));return`data:${t.type||""};base64,${n}`}let An,lr,Bt,En;function ur(t,e=1/0,n=null){lr||(lr=new ta(2,2,1,1)),Bt||(Bt=new yn({uniforms:{blitTexture:new il(t)},vertexShader:` varying vec2 vUv; void main(){ vUv = uv; @@ -76,7 +76,7 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config gl_FragColor = texture2D( blitTexture, vUv); #endif } - `})),Bt.uniforms.blitTexture.value=t,Bt.defines.IS_SRGB="colorSpace"in t?t.colorSpace==="srgb":t.encoding===3001,Bt.needsUpdate=!0,En||(En=new Pt(lr,Bt),En.frustrumCulled=!1);const r=new Et,i=new Pr;i.add(En),n||(n=_n=new ol({antialias:!1})),n.setSize(Math.min(t.image.width,e),Math.min(t.image.height,e)),n.clear(),n.render(i,r);const o=new zn(n.domElement);return o.minFilter=t.minFilter,o.magFilter=t.magFilter,o.wrapS=t.wrapS,o.wrapT=t.wrapT,o.name=t.name,_n&&(_n.dispose(),_n=null),o}const ji={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class bs{constructor(){this.pluginCallbacks=[],this.register(function(e){return new Gu(e)}),this.register(function(e){return new $u(e)}),this.register(function(e){return new Ku(e)}),this.register(function(e){return new Wu(e)}),this.register(function(e){return new Xu(e)}),this.register(function(e){return new Qu(e)}),this.register(function(e){return new Yu(e)}),this.register(function(e){return new qu(e)}),this.register(function(e){return new Zu(e)}),this.register(function(e){return new Ju(e)}),this.register(function(e){return new ec(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,n,r,i){const o=new Hu,s=[];for(let a=0,l=this.pluginCallbacks.length;at.times[t.times.length-1]){if(Math.abs(t.times[t.times.length-1]-e)<.001)return t.times.length-1;r[r.length-1]=e,r.set(t.times,0),i.set(t.values,0),i.set(o.evaluate(e),t.values.length),s=r.length-1}else for(let a=0;ae){r.set(t.times.slice(0,a+1),0),r[a+1]=e,r.set(t.times.slice(a+1),a+2),i.set(t.values.slice(0,(a+1)*n),0),i.set(o.evaluate(e),(a+1)*n),i.set(t.values.slice((a+1)*n),(a+2)*n),s=a+1;break}}return t.times=r,t.values=i,s},mergeMorphTargetTracks:function(t,e){const n=[],r={},i=t.tracks;for(let o=0;o4?s=t.array[i*t.itemSize+o]:(o===0?s=t.getX(i):o===1?s=t.getY(i):o===2?s=t.getZ(i):o===3&&(s=t.getW(i)),t.normalized===!0&&(s=Dt.normalize(s,t.array))),r.min[o]=Math.min(r.min[o],s),r.max[o]=Math.max(r.max[o],s)}return r}function ws(t){return Math.ceil(t/4)*4}function fr(t,e=0){const n=ws(t.byteLength);if(n!==t.byteLength){const r=new Uint8Array(n);if(r.set(new Uint8Array(t)),e!==0)for(let i=t.byteLength;i"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function Yi(t,e){if(t.toBlob!==void 0)return new Promise(r=>t.toBlob(r,e));let n;return e==="image/jpeg"?n=.92:e==="image/webp"&&(n=.8),t.convertToBlob({type:e,quality:n})}class Hu{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map}}setPlugins(e){this.plugins=e}async write(e,n,r={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},r),this.options.animations.length>0&&(this.options.trs=!0),this.processInput(e),await Promise.all(this.pending);const i=this,o=i.buffers,s=i.json;r=i.options;const a=i.extensionsUsed,l=i.extensionsRequired,u=new Blob(o,{type:"application/octet-stream"}),c=Object.keys(a),f=Object.keys(l);c.length>0&&(s.extensionsUsed=c),f.length>0&&(s.extensionsRequired=f),s.buffers&&s.buffers.length>0&&(s.buffers[0].byteLength=u.size),r.binary===!0?u.arrayBuffer().then(p=>{const d=fr(p),b=new DataView(new ArrayBuffer(Gi));b.setUint32(0,d.byteLength,!0),b.setUint32(4,Bu,!0);const x=fr(Uu(JSON.stringify(s)),32),v=new DataView(new ArrayBuffer(Gi));v.setUint32(0,x.byteLength,!0),v.setUint32(4,zu,!0);const T=new ArrayBuffer(Hi),I=new DataView(T);I.setUint32(0,Ou,!0),I.setUint32(4,Fu,!0);const _=Hi+v.byteLength+x.byteLength+b.byteLength+d.byteLength;I.setUint32(8,_,!0),new Blob([T,v,x,b,d],{type:"application/octet-stream"}).arrayBuffer().then(n)}):s.buffers&&s.buffers.length>0?Ui(u).then(p=>{s.buffers[0].uri=p,n(s)}):n(s)}serializeUserData(e,n){if(Object.keys(e.userData).length===0)return;const r=this.options,i=this.extensionsUsed;try{const o=JSON.parse(JSON.stringify(e.userData));if(r.includeCustomExtensions&&o.gltfExtensions){n.extensions===void 0&&(n.extensions={});for(const s in o.gltfExtensions)n.extensions[s]=o.gltfExtensions[s],i[s]=!0;delete o.gltfExtensions}Object.keys(o).length>0&&(n.extras=o)}catch(o){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+o.message)}}getUID(e,n=!1){if(this.uids.has(e)===!1){const r=new Map;r.set(!0,this.uid++),r.set(!1,this.uid++),this.uids.set(e,r)}return this.uids.get(e).get(n)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const n=new se;for(let r=0,i=e.count;r5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const n=this.cache;if(n.attributesNormalized.has(e))return n.attributesNormalized.get(e);const r=e.clone(),i=new se;for(let o=0,s=r.count;o4?b=e.array[p*e.itemSize+d]:(d===0?b=e.getX(p):d===1?b=e.getY(p):d===2?b=e.getZ(p):d===3&&(b=e.getW(p)),e.normalized===!0&&(b=Dt.normalize(b,e.array))),n===me.FLOAT?u.setFloat32(c,b,!0):n===me.INT?u.setInt32(c,b,!0):n===me.UNSIGNED_INT?u.setUint32(c,b,!0):n===me.SHORT?u.setInt16(c,b,!0):n===me.UNSIGNED_SHORT?u.setUint16(c,b,!0):n===me.BYTE?u.setInt8(c,b):n===me.UNSIGNED_BYTE&&u.setUint8(c,b),c+=a}const f={buffer:this.processBuffer(u.buffer),byteOffset:this.byteOffset,byteLength:l};return o!==void 0&&(f.target=o),o===me.ARRAY_BUFFER&&(f.byteStride=e.itemSize*a),this.byteOffset+=l,s.bufferViews.push(f),{id:s.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const n=this,r=n.json;return r.bufferViews||(r.bufferViews=[]),e.arrayBuffer().then(i=>{const o=fr(i),s={buffer:n.processBuffer(o),byteOffset:n.byteOffset,byteLength:o.byteLength};return n.byteOffset+=o.byteLength,r.bufferViews.push(s)-1})}processAccessor(e,n,r,i){const o=this.json,s={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let a;if(e.array.constructor===Float32Array)a=me.FLOAT;else if(e.array.constructor===Int32Array)a=me.INT;else if(e.array.constructor===Uint32Array)a=me.UNSIGNED_INT;else if(e.array.constructor===Int16Array)a=me.SHORT;else if(e.array.constructor===Uint16Array)a=me.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)a=me.BYTE;else if(e.array.constructor===Uint8Array)a=me.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(r===void 0&&(r=0),i===void 0&&(i=e.count),i===0)return null;const l=Vu(e,r,i);let u;n!==void 0&&(u=e===n.index?me.ELEMENT_ARRAY_BUFFER:me.ARRAY_BUFFER);const c=this.processBufferView(e,a,r,i,u),f={bufferView:c.id,byteOffset:c.byteOffset,componentType:a,count:i,max:l.max,min:l.min,type:s[e.itemSize]};return e.normalized===!0&&(f.normalized=!0),o.accessors||(o.accessors=[]),o.accessors.push(f)-1}processImage(e,n,r,i="image/png"){if(e!==null){const o=this,s=o.cache,a=o.json,l=o.options,u=o.pending;s.images.has(e)||s.images.set(e,{});const c=s.images.get(e),f=i+":flipY/"+r.toString();if(c[f]!==void 0)return c[f];a.images||(a.images=[]);const p={mimeType:i},d=$i();d.width=Math.min(e.width,l.maxTextureSize),d.height=Math.min(e.height,l.maxTextureSize);const b=d.getContext("2d");if(r===!0&&(b.translate(0,d.height),b.scale(1,-1)),e.data!==void 0){n!==Lr&&console.error("GLTFExporter: Only RGBAFormat is supported.",n),(e.width>l.maxTextureSize||e.height>l.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const v=new Uint8ClampedArray(e.height*e.width*4);for(let T=0;To.processBufferViewImage(v)).then(v=>{p.bufferView=v})):d.toDataURL!==void 0?p.uri=d.toDataURL(i):u.push(Yi(d,i).then(Ui).then(v=>{p.uri=v}));const x=a.images.push(p)-1;return c[f]=x,x}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const n=this.json;n.samplers||(n.samplers=[]);const r={magFilter:Je[e.magFilter],minFilter:Je[e.minFilter],wrapS:Je[e.wrapS],wrapT:Je[e.wrapT]};return n.samplers.push(r)-1}processTexture(e){const n=this.options,r=this.cache,i=this.json;if(r.textures.has(e))return r.textures.get(e);i.textures||(i.textures=[]),e instanceof er&&(e=ur(e,n.maxTextureSize));let o=e.userData.mimeType;o==="image/webp"&&(o="image/png");const s={sampler:this.processSampler(e),source:this.processImage(e.image,e.format,e.flipY,o)};e.name&&(s.name=e.name),this._invokeAll(function(l){l.writeTexture&&l.writeTexture(e,s)});const a=i.textures.push(s)-1;return r.textures.set(e,a),a}processMaterial(e){const n=this.cache,r=this.json;if(n.materials.has(e))return n.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;r.materials||(r.materials=[]);const i={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const o=e.color.toArray().concat([e.opacity]);if(un(o,[1,1,1,1])||(i.pbrMetallicRoughness.baseColorFactor=o),e.isMeshStandardMaterial?(i.pbrMetallicRoughness.metallicFactor=e.metalness,i.pbrMetallicRoughness.roughnessFactor=e.roughness):(i.pbrMetallicRoughness.metallicFactor=.5,i.pbrMetallicRoughness.roughnessFactor=.5),e.metalnessMap||e.roughnessMap){const a=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),l={index:this.processTexture(a),channel:a.channel};this.applyTextureTransform(l,a),i.pbrMetallicRoughness.metallicRoughnessTexture=l}if(e.map){const a={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(a,e.map),i.pbrMetallicRoughness.baseColorTexture=a}if(e.emissive){const a=e.emissive;if(Math.max(a.r,a.g,a.b)>0&&(i.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const l={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(l,e.emissiveMap),i.emissiveTexture=l}}if(e.normalMap){const a={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(a.scale=e.normalScale.x),this.applyTextureTransform(a,e.normalMap),i.normalTexture=a}if(e.aoMap){const a={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(a.strength=e.aoMapIntensity),this.applyTextureTransform(a,e.aoMap),i.occlusionTexture=a}e.transparent?i.alphaMode="BLEND":e.alphaTest>0&&(i.alphaMode="MASK",i.alphaCutoff=e.alphaTest),e.side===qn&&(i.doubleSided=!0),e.name!==""&&(i.name=e.name),this.serializeUserData(e,i),this._invokeAll(function(a){a.writeMaterial&&a.writeMaterial(e,i)});const s=r.materials.push(i)-1;return n.materials.set(e,s),s}processMesh(e){const n=this.cache,r=this.json,i=[e.geometry.uuid];if(Array.isArray(e.material))for(let _=0,C=e.material.length;_=152?{uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3"}:{uv:"TEXCOORD_0",uv2:"TEXCOORD_1"},color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},d=s.getAttribute("normal");d!==void 0&&!this.isNormalizedNormalAttribute(d)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),s.setAttribute("normal",this.createNormalizedNormalAttribute(d)));let b=null;for(let _ in s.attributes){if(_.slice(0,5)==="morph")continue;const C=s.attributes[_];if(_=p[_]||_.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(_)||(_="_"+_),n.attributes.has(this.getUID(C))){u[_]=n.attributes.get(this.getUID(C));continue}b=null;const P=C.array;_==="JOINTS_0"&&!(P instanceof Uint16Array)&&!(P instanceof Uint8Array)&&(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),b=new Nt(new Uint16Array(P),C.itemSize,C.normalized));const h=this.processAccessor(b||C,s);h!==null&&(_.startsWith("_")||this.detectMeshQuantization(_,C),u[_]=h,n.attributes.set(this.getUID(C),h))}if(d!==void 0&&s.setAttribute("normal",d),Object.keys(u).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const _=[],C=[],P={};if(e.morphTargetDictionary!==void 0)for(const h in e.morphTargetDictionary)P[e.morphTargetDictionary[h]]=h;for(let h=0;h0&&(l.extras={},l.extras.targetNames=C)}const x=Array.isArray(e.material);if(x&&s.groups.length===0)return null;const v=x?e.material:[e.material],T=x?s.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let _=0,C=T.length;_0&&(P.targets=f),s.index!==null){let M=this.getUID(s.index);(T[_].start!==void 0||T[_].count!==void 0)&&(M+=":"+T[_].start+":"+T[_].count),n.attributes.has(M)?P.indices=n.attributes.get(M):(P.indices=this.processAccessor(s.index,s,T[_].start,T[_].count),n.attributes.set(M,P.indices)),P.indices===null&&delete P.indices}const h=this.processMaterial(v[T[_].materialIndex]);h!==null&&(P.material=h),c.push(P)}l.primitives=c,r.meshes||(r.meshes=[]),this._invokeAll(function(_){_.writeMesh&&_.writeMesh(e,l)});const I=r.meshes.push(l)-1;return n.meshes.set(o,I),I}detectMeshQuantization(e,n){if(this.extensionsUsed[cr])return;let r;switch(n.array.constructor){case Int8Array:r="byte";break;case Uint8Array:r="unsigned byte";break;case Int16Array:r="short";break;case Uint16Array:r="unsigned short";break;default:return}n.normalized&&(r+=" normalized");const i=e.split("_",1)[0];ji[i]&&ji[i].includes(r)&&(this.extensionsUsed[cr]=!0,this.extensionsRequired[cr]=!0)}processCamera(e){const n=this.json;n.cameras||(n.cameras=[]);const r=e.isOrthographicCamera,i={type:r?"orthographic":"perspective"};return r?i.orthographic={xmag:e.right*2,ymag:e.top*2,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:i.perspective={aspectRatio:e.aspect,yfov:Dt.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(i.name=e.type),n.cameras.push(i)-1}processAnimation(e,n){const r=this.json,i=this.nodeMap;r.animations||(r.animations=[]),e=bs.Utils.mergeMorphTargetTracks(e.clone(),n);const o=e.tracks,s=[],a=[];for(let l=0;l0){const a=[];for(let l=0,u=e.children.length;l0&&(o.children=a)}this._invokeAll(function(a){a.writeNode&&a.writeNode(e,o)});const s=n.nodes.push(o)-1;return i.set(e,s),s}processScene(e){const n=this.json,r=this.options;n.scenes||(n.scenes=[],n.scene=0);const i={};e.name!==""&&(i.name=e.name),n.scenes.push(i);const o=[];for(let s=0,a=e.children.length;s0&&(i.nodes=o),this.serializeUserData(e,i)}processObjects(e){const n=new Pr;n.name="AuxScene";for(let r=0;r0&&this.processObjects(r);for(let i=0;i0&&(s.range=e.distance)):e.isSpotLight&&(s.type="spot",e.distance>0&&(s.range=e.distance),s.spot={},s.spot.innerConeAngle=(e.penumbra-1)*e.angle*-1,s.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),o[this.name]||(i.extensions=i.extensions||{},i.extensions[this.name]={lights:[]},o[this.name]=!0);const a=i.extensions[this.name].lights;a.push(s),n.extensions=n.extensions||{},n.extensions[this.name]={light:a.length-1}}}let $u=class{constructor(t){this.writer=t,this.name="KHR_materials_unlit"}writeMaterial(t,e){if(!t.isMeshBasicMaterial)return;const n=this.writer.extensionsUsed;e.extensions=e.extensions||{},e.extensions[this.name]={},n[this.name]=!0,e.pbrMetallicRoughness.metallicFactor=0,e.pbrMetallicRoughness.roughnessFactor=.9}},Yu=class{constructor(t){this.writer=t,this.name="KHR_materials_clearcoat"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.clearcoat===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.clearcoatFactor=t.clearcoat,t.clearcoatMap){const o={index:n.processTexture(t.clearcoatMap),texCoord:t.clearcoatMap.channel};n.applyTextureTransform(o,t.clearcoatMap),i.clearcoatTexture=o}if(i.clearcoatRoughnessFactor=t.clearcoatRoughness,t.clearcoatRoughnessMap){const o={index:n.processTexture(t.clearcoatRoughnessMap),texCoord:t.clearcoatRoughnessMap.channel};n.applyTextureTransform(o,t.clearcoatRoughnessMap),i.clearcoatRoughnessTexture=o}if(t.clearcoatNormalMap){const o={index:n.processTexture(t.clearcoatNormalMap),texCoord:t.clearcoatNormalMap.channel};n.applyTextureTransform(o,t.clearcoatNormalMap),i.clearcoatNormalTexture=o}e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},qu=class{constructor(t){this.writer=t,this.name="KHR_materials_iridescence"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.iridescence===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.iridescenceFactor=t.iridescence,t.iridescenceMap){const o={index:n.processTexture(t.iridescenceMap),texCoord:t.iridescenceMap.channel};n.applyTextureTransform(o,t.iridescenceMap),i.iridescenceTexture=o}if(i.iridescenceIor=t.iridescenceIOR,i.iridescenceThicknessMinimum=t.iridescenceThicknessRange[0],i.iridescenceThicknessMaximum=t.iridescenceThicknessRange[1],t.iridescenceThicknessMap){const o={index:n.processTexture(t.iridescenceThicknessMap),texCoord:t.iridescenceThicknessMap.channel};n.applyTextureTransform(o,t.iridescenceThicknessMap),i.iridescenceThicknessTexture=o}e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Ku=class{constructor(t){this.writer=t,this.name="KHR_materials_transmission"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.transmission===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.transmissionFactor=t.transmission,t.transmissionMap){const o={index:n.processTexture(t.transmissionMap),texCoord:t.transmissionMap.channel};n.applyTextureTransform(o,t.transmissionMap),i.transmissionTexture=o}e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Wu=class{constructor(t){this.writer=t,this.name="KHR_materials_volume"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.transmission===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.thicknessFactor=t.thickness,t.thicknessMap){const o={index:n.processTexture(t.thicknessMap),texCoord:t.thicknessMap.channel};n.applyTextureTransform(o,t.thicknessMap),i.thicknessTexture=o}i.attenuationDistance=t.attenuationDistance,i.attenuationColor=t.attenuationColor.toArray(),e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Xu=class{constructor(t){this.writer=t,this.name="KHR_materials_ior"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.ior===1.5)return;const n=this.writer.extensionsUsed,r={};r.ior=t.ior,e.extensions=e.extensions||{},e.extensions[this.name]=r,n[this.name]=!0}},Qu=class{constructor(t){this.writer=t,this.name="KHR_materials_specular"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.specularIntensity===1&&t.specularColor.equals(Du)&&!t.specularIntensityMap&&!t.specularColorTexture)return;const n=this.writer,r=n.extensionsUsed,i={};if(t.specularIntensityMap){const o={index:n.processTexture(t.specularIntensityMap),texCoord:t.specularIntensityMap.channel};n.applyTextureTransform(o,t.specularIntensityMap),i.specularTexture=o}if(t.specularColorMap){const o={index:n.processTexture(t.specularColorMap),texCoord:t.specularColorMap.channel};n.applyTextureTransform(o,t.specularColorMap),i.specularColorTexture=o}i.specularFactor=t.specularIntensity,i.specularColorFactor=t.specularColor.toArray(),e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Zu=class{constructor(t){this.writer=t,this.name="KHR_materials_sheen"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.sheen==0)return;const n=this.writer,r=n.extensionsUsed,i={};if(t.sheenRoughnessMap){const o={index:n.processTexture(t.sheenRoughnessMap),texCoord:t.sheenRoughnessMap.channel};n.applyTextureTransform(o,t.sheenRoughnessMap),i.sheenRoughnessTexture=o}if(t.sheenColorMap){const o={index:n.processTexture(t.sheenColorMap),texCoord:t.sheenColorMap.channel};n.applyTextureTransform(o,t.sheenColorMap),i.sheenColorTexture=o}i.sheenRoughnessFactor=t.sheenRoughness,i.sheenColorFactor=t.sheenColor.toArray(),e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Ju=class{constructor(t){this.writer=t,this.name="KHR_materials_anisotropy"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.anisotropy==0)return;const n=this.writer,r=n.extensionsUsed,i={};if(t.anisotropyMap){const o={index:n.processTexture(t.anisotropyMap)};n.applyTextureTransform(o,t.anisotropyMap),i.anisotropyTexture=o}i.anisotropyStrength=t.anisotropy,i.anisotropyRotation=t.anisotropyRotation,e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},ec=class{constructor(t){this.writer=t,this.name="KHR_materials_emissive_strength"}writeMaterial(t,e){if(!t.isMeshStandardMaterial||t.emissiveIntensity===1)return;const n=this.writer.extensionsUsed,r={};r.emissiveStrength=t.emissiveIntensity,e.extensions=e.extensions||{},e.extensions[this.name]=r,n[this.name]=!0}};var xn=Uint8Array,Ts=Uint16Array,tc=Uint32Array,nc=new xn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),rc=new xn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ks=function(t,e){for(var n=new Ts(31),r=0;r<31;++r)n[r]=e+=1<>>1|(Ne&21845)<<1;wt=(wt&52428)>>>2|(wt&13107)<<2,wt=(wt&61680)>>>4|(wt&3855)<<4,sc[Ne]=((wt&65280)>>>8|(wt&255)<<8)>>>1}var Wn=new xn(288);for(var Ne=0;Ne<144;++Ne)Wn[Ne]=8;for(var Ne=144;Ne<256;++Ne)Wn[Ne]=9;for(var Ne=256;Ne<280;++Ne)Wn[Ne]=7;for(var Ne=280;Ne<288;++Ne)Wn[Ne]=8;var ac=new xn(32);for(var Ne=0;Ne<32;++Ne)ac[Ne]=5;var lc=new xn(0),uc=typeof TextDecoder<"u"&&new TextDecoder,cc=0;try{uc.decode(lc,{stream:!0}),cc=1}catch{}var fc=Object.defineProperty,dc=(t,e,n)=>e in t?fc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pc=(t,e,n)=>(dc(t,e+"",n),n);const _s=class extends Pt{constructor(t,e={}){super(t),this.isReflector=!0,this.type="Reflector",this.camera=new Et;const n=this,r=e.color!==void 0?new ze(e.color):new ze(8355711),i=e.textureWidth||512,o=e.textureHeight||512,s=e.clipBias||0,a=e.shader||_s.ReflectorShader,l=e.multisample!==void 0?e.multisample:4,u=new Xo,c=new se,f=new se,p=new se,d=new xt,b=new se(0,0,-1),x=new Mt,v=new se,T=new se,I=new Mt,_=new xt,C=this.camera,P=new Ja(i,o,{samples:l,type:el}),h=new yn({uniforms:ri.clone(a.uniforms),fragmentShader:a.fragmentShader,vertexShader:a.vertexShader});h.uniforms.tDiffuse.value=P.texture,h.uniforms.color.value=r,h.uniforms.textureMatrix.value=_,this.material=h,this.onBeforeRender=function(M,y,g){if(f.setFromMatrixPosition(n.matrixWorld),p.setFromMatrixPosition(g.matrixWorld),d.extractRotation(n.matrixWorld),c.set(0,0,1),c.applyMatrix4(d),v.subVectors(f,p),v.dot(c)>0)return;v.reflect(c).negate(),v.add(f),d.extractRotation(g.matrixWorld),b.set(0,0,-1),b.applyMatrix4(d),b.add(p),T.subVectors(f,b),T.reflect(c).negate(),T.add(f),C.position.copy(v),C.up.set(0,1,0),C.up.applyMatrix4(d),C.up.reflect(c),C.lookAt(T),C.far=g.far,C.updateMatrixWorld(),C.projectionMatrix.copy(g.projectionMatrix),_.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),_.multiply(C.projectionMatrix),_.multiply(C.matrixWorldInverse),_.multiply(n.matrixWorld),u.setFromNormalAndCoplanarPoint(c,f),u.applyMatrix4(C.matrixWorldInverse),x.set(u.normal.x,u.normal.y,u.normal.z,u.constant);const m=C.projectionMatrix;I.x=(Math.sign(x.x)+m.elements[8])/m.elements[0],I.y=(Math.sign(x.y)+m.elements[9])/m.elements[5],I.z=-1,I.w=(1+m.elements[10])/m.elements[14],x.multiplyScalar(2/x.dot(I)),m.elements[2]=x.x,m.elements[6]=x.y,m.elements[10]=x.z+1-s,m.elements[14]=x.w,n.visible=!1;const k=M.getRenderTarget(),E=M.xr.enabled,O=M.shadowMap.autoUpdate,z=M.toneMapping;let D=!1;"outputColorSpace"in M?D=M.outputColorSpace==="srgb":D=M.outputEncoding===3001,M.xr.enabled=!1,M.shadowMap.autoUpdate=!1,"outputColorSpace"in M?M.outputColorSpace="srgb-linear":M.outputEncoding=3e3,M.toneMapping=tl,M.setRenderTarget(P),M.state.buffers.depth.setMask(!0),M.autoClear===!1&&M.clear(),M.render(y,C),M.xr.enabled=E,M.shadowMap.autoUpdate=O,M.toneMapping=z,"outputColorSpace"in M?M.outputColorSpace=D?"srgb":"srgb-linear":M.outputEncoding=D?3001:3e3,M.setRenderTarget(k);const B=g.viewport;B!==void 0&&M.state.viewport(B),n.visible=!0},this.getRenderTarget=function(){return P},this.dispose=function(){P.dispose(),n.material.dispose()}}};let Fr=_s;pc(Fr,"ReflectorShader",{uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:` + `})),Bt.uniforms.blitTexture.value=t,Bt.defines.IS_SRGB="colorSpace"in t?t.colorSpace==="srgb":t.encoding===3001,Bt.needsUpdate=!0,En||(En=new Pt(lr,Bt),En.frustrumCulled=!1);const r=new Et,i=new Pr;i.add(En),n||(n=An=new ol({antialias:!1})),n.setSize(Math.min(t.image.width,e),Math.min(t.image.height,e)),n.clear(),n.render(i,r);const o=new Fn(n.domElement);return o.minFilter=t.minFilter,o.magFilter=t.magFilter,o.wrapS=t.wrapS,o.wrapT=t.wrapT,o.name=t.name,An&&(An.dispose(),An=null),o}const ji={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class ba{constructor(){this.pluginCallbacks=[],this.register(function(e){return new Gu(e)}),this.register(function(e){return new $u(e)}),this.register(function(e){return new Ku(e)}),this.register(function(e){return new Wu(e)}),this.register(function(e){return new Xu(e)}),this.register(function(e){return new Qu(e)}),this.register(function(e){return new qu(e)}),this.register(function(e){return new Yu(e)}),this.register(function(e){return new Zu(e)}),this.register(function(e){return new Ju(e)}),this.register(function(e){return new ec(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,n,r,i){const o=new Hu,a=[];for(let s=0,l=this.pluginCallbacks.length;st.times[t.times.length-1]){if(Math.abs(t.times[t.times.length-1]-e)<.001)return t.times.length-1;r[r.length-1]=e,r.set(t.times,0),i.set(t.values,0),i.set(o.evaluate(e),t.values.length),a=r.length-1}else for(let s=0;se){r.set(t.times.slice(0,s+1),0),r[s+1]=e,r.set(t.times.slice(s+1),s+2),i.set(t.values.slice(0,(s+1)*n),0),i.set(o.evaluate(e),(s+1)*n),i.set(t.values.slice((s+1)*n),(s+2)*n),a=s+1;break}}return t.times=r,t.values=i,a},mergeMorphTargetTracks:function(t,e){const n=[],r={},i=t.tracks;for(let o=0;o4?a=t.array[i*t.itemSize+o]:(o===0?a=t.getX(i):o===1?a=t.getY(i):o===2?a=t.getZ(i):o===3&&(a=t.getW(i)),t.normalized===!0&&(a=Dt.normalize(a,t.array))),r.min[o]=Math.min(r.min[o],a),r.max[o]=Math.max(r.max[o],a)}return r}function wa(t){return Math.ceil(t/4)*4}function fr(t,e=0){const n=wa(t.byteLength);if(n!==t.byteLength){const r=new Uint8Array(n);if(r.set(new Uint8Array(t)),e!==0)for(let i=t.byteLength;i"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function qi(t,e){if(t.toBlob!==void 0)return new Promise(r=>t.toBlob(r,e));let n;return e==="image/jpeg"?n=.92:e==="image/webp"&&(n=.8),t.convertToBlob({type:e,quality:n})}class Hu{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter"}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map}}setPlugins(e){this.plugins=e}async write(e,n,r={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},r),this.options.animations.length>0&&(this.options.trs=!0),this.processInput(e),await Promise.all(this.pending);const i=this,o=i.buffers,a=i.json;r=i.options;const s=i.extensionsUsed,l=i.extensionsRequired,u=new Blob(o,{type:"application/octet-stream"}),c=Object.keys(s),f=Object.keys(l);c.length>0&&(a.extensionsUsed=c),f.length>0&&(a.extensionsRequired=f),a.buffers&&a.buffers.length>0&&(a.buffers[0].byteLength=u.size),r.binary===!0?u.arrayBuffer().then(p=>{const d=fr(p),b=new DataView(new ArrayBuffer(Gi));b.setUint32(0,d.byteLength,!0),b.setUint32(4,Bu,!0);const x=fr(Uu(JSON.stringify(a)),32),v=new DataView(new ArrayBuffer(Gi));v.setUint32(0,x.byteLength,!0),v.setUint32(4,Fu,!0);const T=new ArrayBuffer(Hi),I=new DataView(T);I.setUint32(0,Ou,!0),I.setUint32(4,zu,!0);const A=Hi+v.byteLength+x.byteLength+b.byteLength+d.byteLength;I.setUint32(8,A,!0),new Blob([T,v,x,b,d],{type:"application/octet-stream"}).arrayBuffer().then(n)}):a.buffers&&a.buffers.length>0?Ui(u).then(p=>{a.buffers[0].uri=p,n(a)}):n(a)}serializeUserData(e,n){if(Object.keys(e.userData).length===0)return;const r=this.options,i=this.extensionsUsed;try{const o=JSON.parse(JSON.stringify(e.userData));if(r.includeCustomExtensions&&o.gltfExtensions){n.extensions===void 0&&(n.extensions={});for(const a in o.gltfExtensions)n.extensions[a]=o.gltfExtensions[a],i[a]=!0;delete o.gltfExtensions}Object.keys(o).length>0&&(n.extras=o)}catch(o){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+o.message)}}getUID(e,n=!1){if(this.uids.has(e)===!1){const r=new Map;r.set(!0,this.uid++),r.set(!1,this.uid++),this.uids.set(e,r)}return this.uids.get(e).get(n)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const n=new ae;for(let r=0,i=e.count;r5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const n=this.cache;if(n.attributesNormalized.has(e))return n.attributesNormalized.get(e);const r=e.clone(),i=new ae;for(let o=0,a=r.count;o4?b=e.array[p*e.itemSize+d]:(d===0?b=e.getX(p):d===1?b=e.getY(p):d===2?b=e.getZ(p):d===3&&(b=e.getW(p)),e.normalized===!0&&(b=Dt.normalize(b,e.array))),n===me.FLOAT?u.setFloat32(c,b,!0):n===me.INT?u.setInt32(c,b,!0):n===me.UNSIGNED_INT?u.setUint32(c,b,!0):n===me.SHORT?u.setInt16(c,b,!0):n===me.UNSIGNED_SHORT?u.setUint16(c,b,!0):n===me.BYTE?u.setInt8(c,b):n===me.UNSIGNED_BYTE&&u.setUint8(c,b),c+=s}const f={buffer:this.processBuffer(u.buffer),byteOffset:this.byteOffset,byteLength:l};return o!==void 0&&(f.target=o),o===me.ARRAY_BUFFER&&(f.byteStride=e.itemSize*s),this.byteOffset+=l,a.bufferViews.push(f),{id:a.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const n=this,r=n.json;return r.bufferViews||(r.bufferViews=[]),e.arrayBuffer().then(i=>{const o=fr(i),a={buffer:n.processBuffer(o),byteOffset:n.byteOffset,byteLength:o.byteLength};return n.byteOffset+=o.byteLength,r.bufferViews.push(a)-1})}processAccessor(e,n,r,i){const o=this.json,a={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let s;if(e.array.constructor===Float32Array)s=me.FLOAT;else if(e.array.constructor===Int32Array)s=me.INT;else if(e.array.constructor===Uint32Array)s=me.UNSIGNED_INT;else if(e.array.constructor===Int16Array)s=me.SHORT;else if(e.array.constructor===Uint16Array)s=me.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)s=me.BYTE;else if(e.array.constructor===Uint8Array)s=me.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(r===void 0&&(r=0),i===void 0&&(i=e.count),i===0)return null;const l=Vu(e,r,i);let u;n!==void 0&&(u=e===n.index?me.ELEMENT_ARRAY_BUFFER:me.ARRAY_BUFFER);const c=this.processBufferView(e,s,r,i,u),f={bufferView:c.id,byteOffset:c.byteOffset,componentType:s,count:i,max:l.max,min:l.min,type:a[e.itemSize]};return e.normalized===!0&&(f.normalized=!0),o.accessors||(o.accessors=[]),o.accessors.push(f)-1}processImage(e,n,r,i="image/png"){if(e!==null){const o=this,a=o.cache,s=o.json,l=o.options,u=o.pending;a.images.has(e)||a.images.set(e,{});const c=a.images.get(e),f=i+":flipY/"+r.toString();if(c[f]!==void 0)return c[f];s.images||(s.images=[]);const p={mimeType:i},d=$i();d.width=Math.min(e.width,l.maxTextureSize),d.height=Math.min(e.height,l.maxTextureSize);const b=d.getContext("2d");if(r===!0&&(b.translate(0,d.height),b.scale(1,-1)),e.data!==void 0){n!==Lr&&console.error("GLTFExporter: Only RGBAFormat is supported.",n),(e.width>l.maxTextureSize||e.height>l.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const v=new Uint8ClampedArray(e.height*e.width*4);for(let T=0;To.processBufferViewImage(v)).then(v=>{p.bufferView=v})):d.toDataURL!==void 0?p.uri=d.toDataURL(i):u.push(qi(d,i).then(Ui).then(v=>{p.uri=v}));const x=s.images.push(p)-1;return c[f]=x,x}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const n=this.json;n.samplers||(n.samplers=[]);const r={magFilter:Je[e.magFilter],minFilter:Je[e.minFilter],wrapS:Je[e.wrapS],wrapT:Je[e.wrapT]};return n.samplers.push(r)-1}processTexture(e){const n=this.options,r=this.cache,i=this.json;if(r.textures.has(e))return r.textures.get(e);i.textures||(i.textures=[]),e instanceof er&&(e=ur(e,n.maxTextureSize));let o=e.userData.mimeType;o==="image/webp"&&(o="image/png");const a={sampler:this.processSampler(e),source:this.processImage(e.image,e.format,e.flipY,o)};e.name&&(a.name=e.name),this._invokeAll(function(l){l.writeTexture&&l.writeTexture(e,a)});const s=i.textures.push(a)-1;return r.textures.set(e,s),s}processMaterial(e){const n=this.cache,r=this.json;if(n.materials.has(e))return n.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;r.materials||(r.materials=[]);const i={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const o=e.color.toArray().concat([e.opacity]);if(un(o,[1,1,1,1])||(i.pbrMetallicRoughness.baseColorFactor=o),e.isMeshStandardMaterial?(i.pbrMetallicRoughness.metallicFactor=e.metalness,i.pbrMetallicRoughness.roughnessFactor=e.roughness):(i.pbrMetallicRoughness.metallicFactor=.5,i.pbrMetallicRoughness.roughnessFactor=.5),e.metalnessMap||e.roughnessMap){const s=this.buildMetalRoughTexture(e.metalnessMap,e.roughnessMap),l={index:this.processTexture(s),channel:s.channel};this.applyTextureTransform(l,s),i.pbrMetallicRoughness.metallicRoughnessTexture=l}if(e.map){const s={index:this.processTexture(e.map),texCoord:e.map.channel};this.applyTextureTransform(s,e.map),i.pbrMetallicRoughness.baseColorTexture=s}if(e.emissive){const s=e.emissive;if(Math.max(s.r,s.g,s.b)>0&&(i.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const l={index:this.processTexture(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(l,e.emissiveMap),i.emissiveTexture=l}}if(e.normalMap){const s={index:this.processTexture(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(s.scale=e.normalScale.x),this.applyTextureTransform(s,e.normalMap),i.normalTexture=s}if(e.aoMap){const s={index:this.processTexture(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(s.strength=e.aoMapIntensity),this.applyTextureTransform(s,e.aoMap),i.occlusionTexture=s}e.transparent?i.alphaMode="BLEND":e.alphaTest>0&&(i.alphaMode="MASK",i.alphaCutoff=e.alphaTest),e.side===Yn&&(i.doubleSided=!0),e.name!==""&&(i.name=e.name),this.serializeUserData(e,i),this._invokeAll(function(s){s.writeMaterial&&s.writeMaterial(e,i)});const a=r.materials.push(i)-1;return n.materials.set(e,a),a}processMesh(e){const n=this.cache,r=this.json,i=[e.geometry.uuid];if(Array.isArray(e.material))for(let A=0,C=e.material.length;A=152?{uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3"}:{uv:"TEXCOORD_0",uv2:"TEXCOORD_1"},color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},d=a.getAttribute("normal");d!==void 0&&!this.isNormalizedNormalAttribute(d)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),a.setAttribute("normal",this.createNormalizedNormalAttribute(d)));let b=null;for(let A in a.attributes){if(A.slice(0,5)==="morph")continue;const C=a.attributes[A];if(A=p[A]||A.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(A)||(A="_"+A),n.attributes.has(this.getUID(C))){u[A]=n.attributes.get(this.getUID(C));continue}b=null;const P=C.array;A==="JOINTS_0"&&!(P instanceof Uint16Array)&&!(P instanceof Uint8Array)&&(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),b=new Nt(new Uint16Array(P),C.itemSize,C.normalized));const h=this.processAccessor(b||C,a);h!==null&&(A.startsWith("_")||this.detectMeshQuantization(A,C),u[A]=h,n.attributes.set(this.getUID(C),h))}if(d!==void 0&&a.setAttribute("normal",d),Object.keys(u).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const A=[],C=[],P={};if(e.morphTargetDictionary!==void 0)for(const h in e.morphTargetDictionary)P[e.morphTargetDictionary[h]]=h;for(let h=0;h0&&(l.extras={},l.extras.targetNames=C)}const x=Array.isArray(e.material);if(x&&a.groups.length===0)return null;const v=x?e.material:[e.material],T=x?a.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let A=0,C=T.length;A0&&(P.targets=f),a.index!==null){let S=this.getUID(a.index);(T[A].start!==void 0||T[A].count!==void 0)&&(S+=":"+T[A].start+":"+T[A].count),n.attributes.has(S)?P.indices=n.attributes.get(S):(P.indices=this.processAccessor(a.index,a,T[A].start,T[A].count),n.attributes.set(S,P.indices)),P.indices===null&&delete P.indices}const h=this.processMaterial(v[T[A].materialIndex]);h!==null&&(P.material=h),c.push(P)}l.primitives=c,r.meshes||(r.meshes=[]),this._invokeAll(function(A){A.writeMesh&&A.writeMesh(e,l)});const I=r.meshes.push(l)-1;return n.meshes.set(o,I),I}detectMeshQuantization(e,n){if(this.extensionsUsed[cr])return;let r;switch(n.array.constructor){case Int8Array:r="byte";break;case Uint8Array:r="unsigned byte";break;case Int16Array:r="short";break;case Uint16Array:r="unsigned short";break;default:return}n.normalized&&(r+=" normalized");const i=e.split("_",1)[0];ji[i]&&ji[i].includes(r)&&(this.extensionsUsed[cr]=!0,this.extensionsRequired[cr]=!0)}processCamera(e){const n=this.json;n.cameras||(n.cameras=[]);const r=e.isOrthographicCamera,i={type:r?"orthographic":"perspective"};return r?i.orthographic={xmag:e.right*2,ymag:e.top*2,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:i.perspective={aspectRatio:e.aspect,yfov:Dt.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(i.name=e.type),n.cameras.push(i)-1}processAnimation(e,n){const r=this.json,i=this.nodeMap;r.animations||(r.animations=[]),e=ba.Utils.mergeMorphTargetTracks(e.clone(),n);const o=e.tracks,a=[],s=[];for(let l=0;l0){const s=[];for(let l=0,u=e.children.length;l0&&(o.children=s)}this._invokeAll(function(s){s.writeNode&&s.writeNode(e,o)});const a=n.nodes.push(o)-1;return i.set(e,a),a}processScene(e){const n=this.json,r=this.options;n.scenes||(n.scenes=[],n.scene=0);const i={};e.name!==""&&(i.name=e.name),n.scenes.push(i);const o=[];for(let a=0,s=e.children.length;a0&&(i.nodes=o),this.serializeUserData(e,i)}processObjects(e){const n=new Pr;n.name="AuxScene";for(let r=0;r0&&this.processObjects(r);for(let i=0;i0&&(a.range=e.distance)):e.isSpotLight&&(a.type="spot",e.distance>0&&(a.range=e.distance),a.spot={},a.spot.innerConeAngle=(e.penumbra-1)*e.angle*-1,a.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),o[this.name]||(i.extensions=i.extensions||{},i.extensions[this.name]={lights:[]},o[this.name]=!0);const s=i.extensions[this.name].lights;s.push(a),n.extensions=n.extensions||{},n.extensions[this.name]={light:s.length-1}}}let $u=class{constructor(t){this.writer=t,this.name="KHR_materials_unlit"}writeMaterial(t,e){if(!t.isMeshBasicMaterial)return;const n=this.writer.extensionsUsed;e.extensions=e.extensions||{},e.extensions[this.name]={},n[this.name]=!0,e.pbrMetallicRoughness.metallicFactor=0,e.pbrMetallicRoughness.roughnessFactor=.9}},qu=class{constructor(t){this.writer=t,this.name="KHR_materials_clearcoat"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.clearcoat===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.clearcoatFactor=t.clearcoat,t.clearcoatMap){const o={index:n.processTexture(t.clearcoatMap),texCoord:t.clearcoatMap.channel};n.applyTextureTransform(o,t.clearcoatMap),i.clearcoatTexture=o}if(i.clearcoatRoughnessFactor=t.clearcoatRoughness,t.clearcoatRoughnessMap){const o={index:n.processTexture(t.clearcoatRoughnessMap),texCoord:t.clearcoatRoughnessMap.channel};n.applyTextureTransform(o,t.clearcoatRoughnessMap),i.clearcoatRoughnessTexture=o}if(t.clearcoatNormalMap){const o={index:n.processTexture(t.clearcoatNormalMap),texCoord:t.clearcoatNormalMap.channel};n.applyTextureTransform(o,t.clearcoatNormalMap),i.clearcoatNormalTexture=o}e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Yu=class{constructor(t){this.writer=t,this.name="KHR_materials_iridescence"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.iridescence===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.iridescenceFactor=t.iridescence,t.iridescenceMap){const o={index:n.processTexture(t.iridescenceMap),texCoord:t.iridescenceMap.channel};n.applyTextureTransform(o,t.iridescenceMap),i.iridescenceTexture=o}if(i.iridescenceIor=t.iridescenceIOR,i.iridescenceThicknessMinimum=t.iridescenceThicknessRange[0],i.iridescenceThicknessMaximum=t.iridescenceThicknessRange[1],t.iridescenceThicknessMap){const o={index:n.processTexture(t.iridescenceThicknessMap),texCoord:t.iridescenceThicknessMap.channel};n.applyTextureTransform(o,t.iridescenceThicknessMap),i.iridescenceThicknessTexture=o}e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Ku=class{constructor(t){this.writer=t,this.name="KHR_materials_transmission"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.transmission===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.transmissionFactor=t.transmission,t.transmissionMap){const o={index:n.processTexture(t.transmissionMap),texCoord:t.transmissionMap.channel};n.applyTextureTransform(o,t.transmissionMap),i.transmissionTexture=o}e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Wu=class{constructor(t){this.writer=t,this.name="KHR_materials_volume"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.transmission===0)return;const n=this.writer,r=n.extensionsUsed,i={};if(i.thicknessFactor=t.thickness,t.thicknessMap){const o={index:n.processTexture(t.thicknessMap),texCoord:t.thicknessMap.channel};n.applyTextureTransform(o,t.thicknessMap),i.thicknessTexture=o}i.attenuationDistance=t.attenuationDistance,i.attenuationColor=t.attenuationColor.toArray(),e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Xu=class{constructor(t){this.writer=t,this.name="KHR_materials_ior"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.ior===1.5)return;const n=this.writer.extensionsUsed,r={};r.ior=t.ior,e.extensions=e.extensions||{},e.extensions[this.name]=r,n[this.name]=!0}},Qu=class{constructor(t){this.writer=t,this.name="KHR_materials_specular"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.specularIntensity===1&&t.specularColor.equals(Du)&&!t.specularIntensityMap&&!t.specularColorTexture)return;const n=this.writer,r=n.extensionsUsed,i={};if(t.specularIntensityMap){const o={index:n.processTexture(t.specularIntensityMap),texCoord:t.specularIntensityMap.channel};n.applyTextureTransform(o,t.specularIntensityMap),i.specularTexture=o}if(t.specularColorMap){const o={index:n.processTexture(t.specularColorMap),texCoord:t.specularColorMap.channel};n.applyTextureTransform(o,t.specularColorMap),i.specularColorTexture=o}i.specularFactor=t.specularIntensity,i.specularColorFactor=t.specularColor.toArray(),e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Zu=class{constructor(t){this.writer=t,this.name="KHR_materials_sheen"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.sheen==0)return;const n=this.writer,r=n.extensionsUsed,i={};if(t.sheenRoughnessMap){const o={index:n.processTexture(t.sheenRoughnessMap),texCoord:t.sheenRoughnessMap.channel};n.applyTextureTransform(o,t.sheenRoughnessMap),i.sheenRoughnessTexture=o}if(t.sheenColorMap){const o={index:n.processTexture(t.sheenColorMap),texCoord:t.sheenColorMap.channel};n.applyTextureTransform(o,t.sheenColorMap),i.sheenColorTexture=o}i.sheenRoughnessFactor=t.sheenRoughness,i.sheenColorFactor=t.sheenColor.toArray(),e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},Ju=class{constructor(t){this.writer=t,this.name="KHR_materials_anisotropy"}writeMaterial(t,e){if(!t.isMeshPhysicalMaterial||t.anisotropy==0)return;const n=this.writer,r=n.extensionsUsed,i={};if(t.anisotropyMap){const o={index:n.processTexture(t.anisotropyMap)};n.applyTextureTransform(o,t.anisotropyMap),i.anisotropyTexture=o}i.anisotropyStrength=t.anisotropy,i.anisotropyRotation=t.anisotropyRotation,e.extensions=e.extensions||{},e.extensions[this.name]=i,r[this.name]=!0}},ec=class{constructor(t){this.writer=t,this.name="KHR_materials_emissive_strength"}writeMaterial(t,e){if(!t.isMeshStandardMaterial||t.emissiveIntensity===1)return;const n=this.writer.extensionsUsed,r={};r.emissiveStrength=t.emissiveIntensity,e.extensions=e.extensions||{},e.extensions[this.name]=r,n[this.name]=!0}};var xn=Uint8Array,Ta=Uint16Array,tc=Uint32Array,nc=new xn([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),rc=new xn([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ka=function(t,e){for(var n=new Ta(31),r=0;r<31;++r)n[r]=e+=1<>>1|(Ne&21845)<<1;wt=(wt&52428)>>>2|(wt&13107)<<2,wt=(wt&61680)>>>4|(wt&3855)<<4,ac[Ne]=((wt&65280)>>>8|(wt&255)<<8)>>>1}var Wn=new xn(288);for(var Ne=0;Ne<144;++Ne)Wn[Ne]=8;for(var Ne=144;Ne<256;++Ne)Wn[Ne]=9;for(var Ne=256;Ne<280;++Ne)Wn[Ne]=7;for(var Ne=280;Ne<288;++Ne)Wn[Ne]=8;var sc=new xn(32);for(var Ne=0;Ne<32;++Ne)sc[Ne]=5;var lc=new xn(0),uc=typeof TextDecoder<"u"&&new TextDecoder,cc=0;try{uc.decode(lc,{stream:!0}),cc=1}catch{}var fc=Object.defineProperty,dc=(t,e,n)=>e in t?fc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pc=(t,e,n)=>(dc(t,e+"",n),n);const Aa=class extends Pt{constructor(t,e={}){super(t),this.isReflector=!0,this.type="Reflector",this.camera=new Et;const n=this,r=e.color!==void 0?new Fe(e.color):new Fe(8355711),i=e.textureWidth||512,o=e.textureHeight||512,a=e.clipBias||0,s=e.shader||Aa.ReflectorShader,l=e.multisample!==void 0?e.multisample:4,u=new Xo,c=new ae,f=new ae,p=new ae,d=new xt,b=new ae(0,0,-1),x=new Mt,v=new ae,T=new ae,I=new Mt,A=new xt,C=this.camera,P=new Js(i,o,{samples:l,type:el}),h=new yn({uniforms:ri.clone(s.uniforms),fragmentShader:s.fragmentShader,vertexShader:s.vertexShader});h.uniforms.tDiffuse.value=P.texture,h.uniforms.color.value=r,h.uniforms.textureMatrix.value=A,this.material=h,this.onBeforeRender=function(S,y,g){if(f.setFromMatrixPosition(n.matrixWorld),p.setFromMatrixPosition(g.matrixWorld),d.extractRotation(n.matrixWorld),c.set(0,0,1),c.applyMatrix4(d),v.subVectors(f,p),v.dot(c)>0)return;v.reflect(c).negate(),v.add(f),d.extractRotation(g.matrixWorld),b.set(0,0,-1),b.applyMatrix4(d),b.add(p),T.subVectors(f,b),T.reflect(c).negate(),T.add(f),C.position.copy(v),C.up.set(0,1,0),C.up.applyMatrix4(d),C.up.reflect(c),C.lookAt(T),C.far=g.far,C.updateMatrixWorld(),C.projectionMatrix.copy(g.projectionMatrix),A.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),A.multiply(C.projectionMatrix),A.multiply(C.matrixWorldInverse),A.multiply(n.matrixWorld),u.setFromNormalAndCoplanarPoint(c,f),u.applyMatrix4(C.matrixWorldInverse),x.set(u.normal.x,u.normal.y,u.normal.z,u.constant);const m=C.projectionMatrix;I.x=(Math.sign(x.x)+m.elements[8])/m.elements[0],I.y=(Math.sign(x.y)+m.elements[9])/m.elements[5],I.z=-1,I.w=(1+m.elements[10])/m.elements[14],x.multiplyScalar(2/x.dot(I)),m.elements[2]=x.x,m.elements[6]=x.y,m.elements[10]=x.z+1-a,m.elements[14]=x.w,n.visible=!1;const k=S.getRenderTarget(),E=S.xr.enabled,O=S.shadowMap.autoUpdate,F=S.toneMapping;let D=!1;"outputColorSpace"in S?D=S.outputColorSpace==="srgb":D=S.outputEncoding===3001,S.xr.enabled=!1,S.shadowMap.autoUpdate=!1,"outputColorSpace"in S?S.outputColorSpace="srgb-linear":S.outputEncoding=3e3,S.toneMapping=tl,S.setRenderTarget(P),S.state.buffers.depth.setMask(!0),S.autoClear===!1&&S.clear(),S.render(y,C),S.xr.enabled=E,S.shadowMap.autoUpdate=O,S.toneMapping=F,"outputColorSpace"in S?S.outputColorSpace=D?"srgb":"srgb-linear":S.outputEncoding=D?3001:3e3,S.setRenderTarget(k);const B=g.viewport;B!==void 0&&S.state.viewport(B),n.visible=!0},this.getRenderTarget=function(){return P},this.dispose=function(){P.dispose(),n.material.dispose()}}};let zr=Aa;pc(zr,"ReflectorShader",{uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:` uniform mat4 textureMatrix; varying vec4 vUv; @@ -120,7 +120,7 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config #include #include <${fi>=154?"colorspace_fragment":"encodings_fragment"}> - }`});var hc=Object.defineProperty,mc=(t,e,n)=>e in t?hc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Es=(t,e,n)=>(mc(t,typeof e!="symbol"?e+"":e,n),n);const Xn=new Qo,gc=new Float32Array([-1,-1,0,0,0,1,-1,0,1,0,1,1,0,1,1,-1,1,0,0,1]),Ms=new Zo(gc,5);Xn.setIndex([0,1,2,0,2,3]);Xn.setAttribute("position",new ni(Ms,3,0,!1));Xn.setAttribute("uv",new ni(Ms,2,3,!1));const zr=class extends Pt{constructor(){super(zr.Geometry,new Ht({opacity:0,transparent:!0})),this.isLensflare=!0,this.type="Lensflare",this.frustumCulled=!1,this.renderOrder=1/0;const t=new se,e=new se,n=new Ri(new Uint8Array(16*16*3),16,16,Lr);n.minFilter=Lt,n.magFilter=Lt,n.wrapS=Gt,n.wrapT=Gt;const r=new Ri(new Uint8Array(16*16*3),16,16,Lr);r.minFilter=Lt,r.magFilter=Lt,r.wrapS=Gt,r.wrapT=Gt;const i=zr.Geometry,o=new tr({uniforms:{scale:{value:null},screenPosition:{value:null}},vertexShader:` + }`});var hc=Object.defineProperty,mc=(t,e,n)=>e in t?hc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ea=(t,e,n)=>(mc(t,typeof e!="symbol"?e+"":e,n),n);const Xn=new Qo,gc=new Float32Array([-1,-1,0,0,0,1,-1,0,1,0,1,1,0,1,1,-1,1,0,0,1]),Ma=new Zo(gc,5);Xn.setIndex([0,1,2,0,2,3]);Xn.setAttribute("position",new ni(Ma,3,0,!1));Xn.setAttribute("uv",new ni(Ma,2,3,!1));const Fr=class extends Pt{constructor(){super(Fr.Geometry,new Ht({opacity:0,transparent:!0})),this.isLensflare=!0,this.type="Lensflare",this.frustumCulled=!1,this.renderOrder=1/0;const t=new ae,e=new ae,n=new Ri(new Uint8Array(16*16*3),16,16,Lr);n.minFilter=Lt,n.magFilter=Lt,n.wrapS=Gt,n.wrapT=Gt;const r=new Ri(new Uint8Array(16*16*3),16,16,Lr);r.minFilter=Lt,r.magFilter=Lt,r.wrapS=Gt,r.wrapT=Gt;const i=Fr.Geometry,o=new tr({uniforms:{scale:{value:null},screenPosition:{value:null}},vertexShader:` precision highp float; @@ -141,7 +141,7 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); - }`,depthTest:!0,depthWrite:!1,transparent:!1}),s=new tr({uniforms:{map:{value:n},scale:{value:null},screenPosition:{value:null}},vertexShader:` + }`,depthTest:!0,depthWrite:!1,transparent:!1}),a=new tr({uniforms:{map:{value:n},scale:{value:null},screenPosition:{value:null}},vertexShader:` precision highp float; @@ -171,7 +171,7 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config gl_FragColor = texture2D( map, vUV ); - }`,depthTest:!1,depthWrite:!1,transparent:!1}),a=new Pt(i,o),l=[],u=Ss.Shader,c=new tr({uniforms:{map:{value:null},occlusionMap:{value:r},color:{value:new ze(16777215)},scale:{value:new Pe},screenPosition:{value:new se}},vertexShader:u.vertexShader,fragmentShader:u.fragmentShader,blending:nl,transparent:!0,depthWrite:!1}),f=new Pt(i,c);this.addElement=function(v){l.push(v)};const p=new Pe,d=new Pe,b=new rl,x=new Mt;this.onBeforeRender=function(v,T,I){v.getCurrentViewport(x);const _=x.w/x.z,C=x.z/2,P=x.w/2;let h=16/x.w;if(p.set(h*_,h),b.min.set(x.x,x.y),b.max.set(x.x+(x.z-16),x.y+(x.w-16)),e.setFromMatrixPosition(this.matrixWorld),e.applyMatrix4(I.matrixWorldInverse),!(e.z>0)&&(t.copy(e).applyMatrix4(I.projectionMatrix),d.x=x.x+t.x*C+C-8,d.y=x.y+t.y*P+P-8,b.containsPoint(d))){v.copyFramebufferToTexture(d,n);let M=o.uniforms;M.scale.value=p,M.screenPosition.value=t,v.renderBufferDirect(I,null,i,o,a,null),v.copyFramebufferToTexture(d,r),M=s.uniforms,M.scale.value=p,M.screenPosition.value=t,v.renderBufferDirect(I,null,i,s,a,null);const y=-t.x*2,g=-t.y*2;for(let m=0,k=l.length;m0)&&(t.copy(e).applyMatrix4(I.projectionMatrix),d.x=x.x+t.x*C+C-8,d.y=x.y+t.y*P+P-8,b.containsPoint(d))){v.copyFramebufferToTexture(d,n);let S=o.uniforms;S.scale.value=p,S.screenPosition.value=t,v.renderBufferDirect(I,null,i,o,s,null),v.copyFramebufferToTexture(d,r),S=a.uniforms,S.scale.value=p,S.screenPosition.value=t,v.renderBufferDirect(I,null,i,a,s,null);const y=-t.x*2,g=-t.y*2;for(let m=0,k=l.length;me in t?Ta(t,e,{enumerable:!0,config gl_FragColor = texture; gl_FragColor.rgb *= color; - }`});var xc=Object.defineProperty,vc=(t,e,n)=>e in t?xc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Is=(t,e,n)=>(vc(t,typeof e!="symbol"?e+"":e,n),n);const Pn={uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new se},up:{value:new se(0,1,0)}},vertexShader:` + }`});var xc=Object.defineProperty,vc=(t,e,n)=>e in t?xc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ia=(t,e,n)=>(vc(t,typeof e!="symbol"?e+"":e,n),n);const Pn={uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:.005},mieDirectionalG:{value:.8},sunPosition:{value:new ae},up:{value:new ae(0,1,0)}},vertexShader:` uniform vec3 sunPosition; uniform float rayleigh; uniform float turbidity; @@ -382,8 +382,8 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config #include <${fi>=154?"colorspace_fragment":"encodings_fragment"}> } - `},Rs=new yn({name:"SkyShader",fragmentShader:Pn.fragmentShader,vertexShader:Pn.vertexShader,uniforms:ri.clone(Pn.uniforms),side:Va,depthWrite:!1});class Cs extends Pt{constructor(){super(new Za(1,1,1),Rs)}}Is(Cs,"SkyShader",Pn);Is(Cs,"material",Rs);new Ha;new se;new Jo(0,0,0,"YXZ");new se;var bc=Object.defineProperty,wc=(t,e,n)=>e in t?bc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,re=(t,e,n)=>(wc(t,typeof e!="symbol"?e+"":e,n),n);const Mn=new ja,qi=new Xo,Tc=Math.cos(70*(Math.PI/180)),Ki=(t,e)=>(t%e+e)%e;class kc extends Ua{constructor(e,n){super(),re(this,"object"),re(this,"domElement"),re(this,"enabled",!0),re(this,"target",new se),re(this,"minDistance",0),re(this,"maxDistance",1/0),re(this,"minZoom",0),re(this,"maxZoom",1/0),re(this,"minPolarAngle",0),re(this,"maxPolarAngle",Math.PI),re(this,"minAzimuthAngle",-1/0),re(this,"maxAzimuthAngle",1/0),re(this,"enableDamping",!1),re(this,"dampingFactor",.05),re(this,"enableZoom",!0),re(this,"zoomSpeed",1),re(this,"enableRotate",!0),re(this,"rotateSpeed",1),re(this,"enablePan",!0),re(this,"panSpeed",1),re(this,"screenSpacePanning",!0),re(this,"keyPanSpeed",7),re(this,"zoomToCursor",!1),re(this,"autoRotate",!1),re(this,"autoRotateSpeed",2),re(this,"reverseOrbit",!1),re(this,"reverseHorizontalOrbit",!1),re(this,"reverseVerticalOrbit",!1),re(this,"keys",{LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"}),re(this,"mouseButtons",{LEFT:yt.ROTATE,MIDDLE:yt.DOLLY,RIGHT:yt.PAN}),re(this,"touches",{ONE:At.ROTATE,TWO:At.DOLLY_PAN}),re(this,"target0"),re(this,"position0"),re(this,"zoom0"),re(this,"_domElementKeyEvents",null),re(this,"getPolarAngle"),re(this,"getAzimuthalAngle"),re(this,"setPolarAngle"),re(this,"setAzimuthalAngle"),re(this,"getDistance"),re(this,"getZoomScale"),re(this,"listenToKeyEvents"),re(this,"stopListenToKeyEvents"),re(this,"saveState"),re(this,"reset"),re(this,"update"),re(this,"connect"),re(this,"dispose"),re(this,"dollyIn"),re(this,"dollyOut"),re(this,"getScale"),re(this,"setScale"),this.object=e,this.domElement=n,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.getPolarAngle=()=>c.phi,this.getAzimuthalAngle=()=>c.theta,this.setPolarAngle=L=>{let Y=Ki(L,2*Math.PI),J=c.phi;J<0&&(J+=2*Math.PI),Y<0&&(Y+=2*Math.PI);let Ee=Math.abs(Y-J);2*Math.PI-Ee{let Y=Ki(L,2*Math.PI),J=c.theta;J<0&&(J+=2*Math.PI),Y<0&&(Y+=2*Math.PI);let Ee=Math.abs(Y-J);2*Math.PI-Eer.object.position.distanceTo(r.target),this.listenToKeyEvents=L=>{L.addEventListener("keydown",oe),this._domElementKeyEvents=L},this.stopListenToKeyEvents=()=>{this._domElementKeyEvents.removeEventListener("keydown",oe),this._domElementKeyEvents=null},this.saveState=()=>{r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=()=>{r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(i),r.update(),l=a.NONE},this.update=(()=>{const L=new se,Y=new se(0,1,0),J=new Fn().setFromUnitVectors(e.up,Y),Ee=J.clone().invert(),Xe=new se,st=new Fn,Tn=2*Math.PI;return function(){const Ei=r.object.position;J.setFromUnitVectors(e.up,Y),Ee.copy(J).invert(),L.copy(Ei).sub(r.target),L.applyQuaternion(J),c.setFromVector3(L),r.autoRotate&&l===a.NONE&&z(E()),r.enableDamping?(c.theta+=f.theta*r.dampingFactor,c.phi+=f.phi*r.dampingFactor):(c.theta+=f.theta,c.phi+=f.phi);let ht=r.minAzimuthAngle,mt=r.maxAzimuthAngle;isFinite(ht)&&isFinite(mt)&&(ht<-Math.PI?ht+=Tn:ht>Math.PI&&(ht-=Tn),mt<-Math.PI?mt+=Tn:mt>Math.PI&&(mt-=Tn),ht<=mt?c.theta=Math.max(ht,Math.min(mt,c.theta)):c.theta=c.theta>(ht+mt)/2?Math.max(ht,c.theta):Math.min(mt,c.theta)),c.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,c.phi)),c.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(d,r.dampingFactor):r.target.add(d),r.zoomToCursor&&g||r.object.isOrthographicCamera?c.radius=R(c.radius):c.radius=R(c.radius*p),L.setFromSpherical(c),L.applyQuaternion(Ee),Ei.copy(r.target).add(L),r.object.matrixAutoUpdate||r.object.updateMatrix(),r.object.lookAt(r.target),r.enableDamping===!0?(f.theta*=1-r.dampingFactor,f.phi*=1-r.dampingFactor,d.multiplyScalar(1-r.dampingFactor)):(f.set(0,0,0),d.set(0,0,0));let tn=!1;if(r.zoomToCursor&&g){let nn=null;if(r.object instanceof Et&&r.object.isPerspectiveCamera){const rn=L.length();nn=R(rn*p);const kn=rn-nn;r.object.position.addScaledVector(M,kn),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const rn=new se(y.x,y.y,0);rn.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/p)),r.object.updateProjectionMatrix(),tn=!0;const kn=new se(y.x,y.y,0);kn.unproject(r.object),r.object.position.sub(kn).add(rn),r.object.updateMatrixWorld(),nn=L.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;nn!==null&&(r.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(nn).add(r.object.position):(Mn.origin.copy(r.object.position),Mn.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(Mn.direction))u||8*(1-st.dot(r.object.quaternion))>u?(r.dispatchEvent(i),Xe.copy(r.object.position),st.copy(r.object.quaternion),tn=!1,!0):!1}})(),this.connect=L=>{r.domElement=L,r.domElement.style.touchAction="none",r.domElement.addEventListener("contextmenu",He),r.domElement.addEventListener("pointerdown",Me),r.domElement.addEventListener("pointercancel",tt),r.domElement.addEventListener("wheel",K)},this.dispose=()=>{var L,Y,J,Ee,Xe,st;r.domElement&&(r.domElement.style.touchAction="auto"),(L=r.domElement)==null||L.removeEventListener("contextmenu",He),(Y=r.domElement)==null||Y.removeEventListener("pointerdown",Me),(J=r.domElement)==null||J.removeEventListener("pointercancel",tt),(Ee=r.domElement)==null||Ee.removeEventListener("wheel",K),(Xe=r.domElement)==null||Xe.ownerDocument.removeEventListener("pointermove",Ve),(st=r.domElement)==null||st.ownerDocument.removeEventListener("pointerup",tt),r._domElementKeyEvents!==null&&r._domElementKeyEvents.removeEventListener("keydown",oe)};const r=this,i={type:"change"},o={type:"start"},s={type:"end"},a={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let l=a.NONE;const u=1e-6,c=new Ii,f=new Ii;let p=1;const d=new se,b=new Pe,x=new Pe,v=new Pe,T=new Pe,I=new Pe,_=new Pe,C=new Pe,P=new Pe,h=new Pe,M=new se,y=new Pe;let g=!1;const m=[],k={};function E(){return 2*Math.PI/60/60*r.autoRotateSpeed}function O(){return Math.pow(.95,r.zoomSpeed)}function z(L){r.reverseOrbit||r.reverseHorizontalOrbit?f.theta+=L:f.theta-=L}function D(L){r.reverseOrbit||r.reverseVerticalOrbit?f.phi+=L:f.phi-=L}const B=(()=>{const L=new se;return function(Y,J){L.setFromMatrixColumn(J,0),L.multiplyScalar(-Y),d.add(L)}})(),X=(()=>{const L=new se;return function(Y,J){r.screenSpacePanning===!0?L.setFromMatrixColumn(J,1):(L.setFromMatrixColumn(J,0),L.crossVectors(r.object.up,L)),L.multiplyScalar(Y),d.add(L)}})(),Z=(()=>{const L=new se;return function(Y,J){const Ee=r.domElement;if(Ee&&r.object instanceof Et&&r.object.isPerspectiveCamera){const Xe=r.object.position;L.copy(Xe).sub(r.target);let st=L.length();st*=Math.tan(r.object.fov/2*Math.PI/180),B(2*Y*st/Ee.clientHeight,r.object.matrix),X(2*J*st/Ee.clientHeight,r.object.matrix)}else Ee&&r.object instanceof $t&&r.object.isOrthographicCamera?(B(Y*(r.object.right-r.object.left)/r.object.zoom/Ee.clientWidth,r.object.matrix),X(J*(r.object.top-r.object.bottom)/r.object.zoom/Ee.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function Q(L){r.object instanceof Et&&r.object.isPerspectiveCamera||r.object instanceof $t&&r.object.isOrthographicCamera?p=L:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function A(L){Q(p/L)}function te(L){Q(p*L)}function ce(L){if(!r.zoomToCursor||!r.domElement)return;g=!0;const Y=r.domElement.getBoundingClientRect(),J=L.clientX-Y.left,Ee=L.clientY-Y.top,Xe=Y.width,st=Y.height;y.x=J/Xe*2-1,y.y=-(Ee/st)*2+1,M.set(y.x,y.y,1).unproject(r.object).sub(r.object.position).normalize()}function R(L){return Math.max(r.minDistance,Math.min(r.maxDistance,L))}function pe(L){b.set(L.clientX,L.clientY)}function ye(L){ce(L),C.set(L.clientX,L.clientY)}function xe(L){T.set(L.clientX,L.clientY)}function Oe(L){x.set(L.clientX,L.clientY),v.subVectors(x,b).multiplyScalar(r.rotateSpeed);const Y=r.domElement;Y&&(z(2*Math.PI*v.x/Y.clientHeight),D(2*Math.PI*v.y/Y.clientHeight)),b.copy(x),r.update()}function G(L){P.set(L.clientX,L.clientY),h.subVectors(P,C),h.y>0?A(O()):h.y<0&&te(O()),C.copy(P),r.update()}function w(L){I.set(L.clientX,L.clientY),_.subVectors(I,T).multiplyScalar(r.panSpeed),Z(_.x,_.y),T.copy(I),r.update()}function S(L){ce(L),L.deltaY<0?te(O()):L.deltaY>0&&A(O()),r.update()}function N(L){let Y=!1;switch(L.code){case r.keys.UP:Z(0,r.keyPanSpeed),Y=!0;break;case r.keys.BOTTOM:Z(0,-r.keyPanSpeed),Y=!0;break;case r.keys.LEFT:Z(r.keyPanSpeed,0),Y=!0;break;case r.keys.RIGHT:Z(-r.keyPanSpeed,0),Y=!0;break}Y&&(L.preventDefault(),r.update())}function V(){if(m.length==1)b.set(m[0].pageX,m[0].pageY);else{const L=.5*(m[0].pageX+m[1].pageX),Y=.5*(m[0].pageY+m[1].pageY);b.set(L,Y)}}function U(){if(m.length==1)T.set(m[0].pageX,m[0].pageY);else{const L=.5*(m[0].pageX+m[1].pageX),Y=.5*(m[0].pageY+m[1].pageY);T.set(L,Y)}}function q(){const L=m[0].pageX-m[1].pageX,Y=m[0].pageY-m[1].pageY,J=Math.sqrt(L*L+Y*Y);C.set(0,J)}function ne(){r.enableZoom&&q(),r.enablePan&&U()}function ve(){r.enableZoom&&q(),r.enableRotate&&V()}function Ae(L){if(m.length==1)x.set(L.pageX,L.pageY);else{const J=pt(L),Ee=.5*(L.pageX+J.x),Xe=.5*(L.pageY+J.y);x.set(Ee,Xe)}v.subVectors(x,b).multiplyScalar(r.rotateSpeed);const Y=r.domElement;Y&&(z(2*Math.PI*v.x/Y.clientHeight),D(2*Math.PI*v.y/Y.clientHeight)),b.copy(x)}function de(L){if(m.length==1)I.set(L.pageX,L.pageY);else{const Y=pt(L),J=.5*(L.pageX+Y.x),Ee=.5*(L.pageY+Y.y);I.set(J,Ee)}_.subVectors(I,T).multiplyScalar(r.panSpeed),Z(_.x,_.y),T.copy(I)}function be(L){const Y=pt(L),J=L.pageX-Y.x,Ee=L.pageY-Y.y,Xe=Math.sqrt(J*J+Ee*Ee);P.set(0,Xe),h.set(0,Math.pow(P.y/C.y,r.zoomSpeed)),A(h.y),C.copy(P)}function Ie(L){r.enableZoom&&be(L),r.enablePan&&de(L)}function Te(L){r.enableZoom&&be(L),r.enableRotate&&Ae(L)}function Me(L){var Y,J;r.enabled!==!1&&(m.length===0&&((Y=r.domElement)==null||Y.ownerDocument.addEventListener("pointermove",Ve),(J=r.domElement)==null||J.ownerDocument.addEventListener("pointerup",tt)),dt(L),L.pointerType==="touch"?ue(L):en(L))}function Ve(L){r.enabled!==!1&&(L.pointerType==="touch"?we(L):j(L))}function tt(L){var Y,J,Ee;ot(L),m.length===0&&((Y=r.domElement)==null||Y.releasePointerCapture(L.pointerId),(J=r.domElement)==null||J.ownerDocument.removeEventListener("pointermove",Ve),(Ee=r.domElement)==null||Ee.ownerDocument.removeEventListener("pointerup",tt)),r.dispatchEvent(s),l=a.NONE}function en(L){let Y;switch(L.button){case 0:Y=r.mouseButtons.LEFT;break;case 1:Y=r.mouseButtons.MIDDLE;break;case 2:Y=r.mouseButtons.RIGHT;break;default:Y=-1}switch(Y){case yt.DOLLY:if(r.enableZoom===!1)return;ye(L),l=a.DOLLY;break;case yt.ROTATE:if(L.ctrlKey||L.metaKey||L.shiftKey){if(r.enablePan===!1)return;xe(L),l=a.PAN}else{if(r.enableRotate===!1)return;pe(L),l=a.ROTATE}break;case yt.PAN:if(L.ctrlKey||L.metaKey||L.shiftKey){if(r.enableRotate===!1)return;pe(L),l=a.ROTATE}else{if(r.enablePan===!1)return;xe(L),l=a.PAN}break;default:l=a.NONE}l!==a.NONE&&r.dispatchEvent(o)}function j(L){if(r.enabled!==!1)switch(l){case a.ROTATE:if(r.enableRotate===!1)return;Oe(L);break;case a.DOLLY:if(r.enableZoom===!1)return;G(L);break;case a.PAN:if(r.enablePan===!1)return;w(L);break}}function K(L){r.enabled===!1||r.enableZoom===!1||l!==a.NONE&&l!==a.ROTATE||(L.preventDefault(),r.dispatchEvent(o),S(L),r.dispatchEvent(s))}function oe(L){r.enabled===!1||r.enablePan===!1||N(L)}function ue(L){switch(bt(L),m.length){case 1:switch(r.touches.ONE){case At.ROTATE:if(r.enableRotate===!1)return;V(),l=a.TOUCH_ROTATE;break;case At.PAN:if(r.enablePan===!1)return;U(),l=a.TOUCH_PAN;break;default:l=a.NONE}break;case 2:switch(r.touches.TWO){case At.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;ne(),l=a.TOUCH_DOLLY_PAN;break;case At.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;ve(),l=a.TOUCH_DOLLY_ROTATE;break;default:l=a.NONE}break;default:l=a.NONE}l!==a.NONE&&r.dispatchEvent(o)}function we(L){switch(bt(L),l){case a.TOUCH_ROTATE:if(r.enableRotate===!1)return;Ae(L),r.update();break;case a.TOUCH_PAN:if(r.enablePan===!1)return;de(L),r.update();break;case a.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;Ie(L),r.update();break;case a.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;Te(L),r.update();break;default:l=a.NONE}}function He(L){r.enabled!==!1&&L.preventDefault()}function dt(L){m.push(L)}function ot(L){delete k[L.pointerId];for(let Y=0;Y{te(L),r.update()},this.dollyOut=(L=O())=>{A(L),r.update()},this.getScale=()=>p,this.setScale=L=>{Q(L),r.update()},this.getZoomScale=()=>O(),n!==void 0&&this.connect(n),this.update()}}new xt;new se;new Jo;new se;var Ac=Object.defineProperty,_c=(t,e,n)=>e in t?Ac(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,di=(t,e,n)=>(_c(t,typeof e!="symbol"?e+"":e,n),n);class Ns{constructor(e){di(this,"data"),this.data=e}generateShapes(e,n=100,r){const i=[],o={letterSpacing:0,lineHeight:1,...r},s=Ec(e,n,this.data,o);for(let a=0,l=s.length;a + `},Ra=new yn({name:"SkyShader",fragmentShader:Pn.fragmentShader,vertexShader:Pn.vertexShader,uniforms:ri.clone(Pn.uniforms),side:Vs,depthWrite:!1});class Ca extends Pt{constructor(){super(new Zs(1,1,1),Ra)}}Ia(Ca,"SkyShader",Pn);Ia(Ca,"material",Ra);new Hs;new ae;new Jo(0,0,0,"YXZ");new ae;var bc=Object.defineProperty,wc=(t,e,n)=>e in t?bc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,re=(t,e,n)=>(wc(t,typeof e!="symbol"?e+"":e,n),n);const Mn=new js,Yi=new Xo,Tc=Math.cos(70*(Math.PI/180)),Ki=(t,e)=>(t%e+e)%e;class kc extends Us{constructor(e,n){super(),re(this,"object"),re(this,"domElement"),re(this,"enabled",!0),re(this,"target",new ae),re(this,"minDistance",0),re(this,"maxDistance",1/0),re(this,"minZoom",0),re(this,"maxZoom",1/0),re(this,"minPolarAngle",0),re(this,"maxPolarAngle",Math.PI),re(this,"minAzimuthAngle",-1/0),re(this,"maxAzimuthAngle",1/0),re(this,"enableDamping",!1),re(this,"dampingFactor",.05),re(this,"enableZoom",!0),re(this,"zoomSpeed",1),re(this,"enableRotate",!0),re(this,"rotateSpeed",1),re(this,"enablePan",!0),re(this,"panSpeed",1),re(this,"screenSpacePanning",!0),re(this,"keyPanSpeed",7),re(this,"zoomToCursor",!1),re(this,"autoRotate",!1),re(this,"autoRotateSpeed",2),re(this,"reverseOrbit",!1),re(this,"reverseHorizontalOrbit",!1),re(this,"reverseVerticalOrbit",!1),re(this,"keys",{LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"}),re(this,"mouseButtons",{LEFT:yt.ROTATE,MIDDLE:yt.DOLLY,RIGHT:yt.PAN}),re(this,"touches",{ONE:_t.ROTATE,TWO:_t.DOLLY_PAN}),re(this,"target0"),re(this,"position0"),re(this,"zoom0"),re(this,"_domElementKeyEvents",null),re(this,"getPolarAngle"),re(this,"getAzimuthalAngle"),re(this,"setPolarAngle"),re(this,"setAzimuthalAngle"),re(this,"getDistance"),re(this,"getZoomScale"),re(this,"listenToKeyEvents"),re(this,"stopListenToKeyEvents"),re(this,"saveState"),re(this,"reset"),re(this,"update"),re(this,"connect"),re(this,"dispose"),re(this,"dollyIn"),re(this,"dollyOut"),re(this,"getScale"),re(this,"setScale"),this.object=e,this.domElement=n,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.getPolarAngle=()=>c.phi,this.getAzimuthalAngle=()=>c.theta,this.setPolarAngle=L=>{let q=Ki(L,2*Math.PI),J=c.phi;J<0&&(J+=2*Math.PI),q<0&&(q+=2*Math.PI);let Ee=Math.abs(q-J);2*Math.PI-Ee{let q=Ki(L,2*Math.PI),J=c.theta;J<0&&(J+=2*Math.PI),q<0&&(q+=2*Math.PI);let Ee=Math.abs(q-J);2*Math.PI-Eer.object.position.distanceTo(r.target),this.listenToKeyEvents=L=>{L.addEventListener("keydown",oe),this._domElementKeyEvents=L},this.stopListenToKeyEvents=()=>{this._domElementKeyEvents.removeEventListener("keydown",oe),this._domElementKeyEvents=null},this.saveState=()=>{r.target0.copy(r.target),r.position0.copy(r.object.position),r.zoom0=r.object.zoom},this.reset=()=>{r.target.copy(r.target0),r.object.position.copy(r.position0),r.object.zoom=r.zoom0,r.object.updateProjectionMatrix(),r.dispatchEvent(i),r.update(),l=s.NONE},this.update=(()=>{const L=new ae,q=new ae(0,1,0),J=new zn().setFromUnitVectors(e.up,q),Ee=J.clone().invert(),Xe=new ae,at=new zn,Tn=2*Math.PI;return function(){const Ei=r.object.position;J.setFromUnitVectors(e.up,q),Ee.copy(J).invert(),L.copy(Ei).sub(r.target),L.applyQuaternion(J),c.setFromVector3(L),r.autoRotate&&l===s.NONE&&F(E()),r.enableDamping?(c.theta+=f.theta*r.dampingFactor,c.phi+=f.phi*r.dampingFactor):(c.theta+=f.theta,c.phi+=f.phi);let ht=r.minAzimuthAngle,mt=r.maxAzimuthAngle;isFinite(ht)&&isFinite(mt)&&(ht<-Math.PI?ht+=Tn:ht>Math.PI&&(ht-=Tn),mt<-Math.PI?mt+=Tn:mt>Math.PI&&(mt-=Tn),ht<=mt?c.theta=Math.max(ht,Math.min(mt,c.theta)):c.theta=c.theta>(ht+mt)/2?Math.max(ht,c.theta):Math.min(mt,c.theta)),c.phi=Math.max(r.minPolarAngle,Math.min(r.maxPolarAngle,c.phi)),c.makeSafe(),r.enableDamping===!0?r.target.addScaledVector(d,r.dampingFactor):r.target.add(d),r.zoomToCursor&&g||r.object.isOrthographicCamera?c.radius=R(c.radius):c.radius=R(c.radius*p),L.setFromSpherical(c),L.applyQuaternion(Ee),Ei.copy(r.target).add(L),r.object.matrixAutoUpdate||r.object.updateMatrix(),r.object.lookAt(r.target),r.enableDamping===!0?(f.theta*=1-r.dampingFactor,f.phi*=1-r.dampingFactor,d.multiplyScalar(1-r.dampingFactor)):(f.set(0,0,0),d.set(0,0,0));let tn=!1;if(r.zoomToCursor&&g){let nn=null;if(r.object instanceof Et&&r.object.isPerspectiveCamera){const rn=L.length();nn=R(rn*p);const kn=rn-nn;r.object.position.addScaledVector(S,kn),r.object.updateMatrixWorld()}else if(r.object.isOrthographicCamera){const rn=new ae(y.x,y.y,0);rn.unproject(r.object),r.object.zoom=Math.max(r.minZoom,Math.min(r.maxZoom,r.object.zoom/p)),r.object.updateProjectionMatrix(),tn=!0;const kn=new ae(y.x,y.y,0);kn.unproject(r.object),r.object.position.sub(kn).add(rn),r.object.updateMatrixWorld(),nn=L.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),r.zoomToCursor=!1;nn!==null&&(r.screenSpacePanning?r.target.set(0,0,-1).transformDirection(r.object.matrix).multiplyScalar(nn).add(r.object.position):(Mn.origin.copy(r.object.position),Mn.direction.set(0,0,-1).transformDirection(r.object.matrix),Math.abs(r.object.up.dot(Mn.direction))u||8*(1-at.dot(r.object.quaternion))>u?(r.dispatchEvent(i),Xe.copy(r.object.position),at.copy(r.object.quaternion),tn=!1,!0):!1}})(),this.connect=L=>{r.domElement=L,r.domElement.style.touchAction="none",r.domElement.addEventListener("contextmenu",He),r.domElement.addEventListener("pointerdown",Me),r.domElement.addEventListener("pointercancel",tt),r.domElement.addEventListener("wheel",K)},this.dispose=()=>{var L,q,J,Ee,Xe,at;r.domElement&&(r.domElement.style.touchAction="auto"),(L=r.domElement)==null||L.removeEventListener("contextmenu",He),(q=r.domElement)==null||q.removeEventListener("pointerdown",Me),(J=r.domElement)==null||J.removeEventListener("pointercancel",tt),(Ee=r.domElement)==null||Ee.removeEventListener("wheel",K),(Xe=r.domElement)==null||Xe.ownerDocument.removeEventListener("pointermove",Ve),(at=r.domElement)==null||at.ownerDocument.removeEventListener("pointerup",tt),r._domElementKeyEvents!==null&&r._domElementKeyEvents.removeEventListener("keydown",oe)};const r=this,i={type:"change"},o={type:"start"},a={type:"end"},s={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6};let l=s.NONE;const u=1e-6,c=new Ii,f=new Ii;let p=1;const d=new ae,b=new Pe,x=new Pe,v=new Pe,T=new Pe,I=new Pe,A=new Pe,C=new Pe,P=new Pe,h=new Pe,S=new ae,y=new Pe;let g=!1;const m=[],k={};function E(){return 2*Math.PI/60/60*r.autoRotateSpeed}function O(){return Math.pow(.95,r.zoomSpeed)}function F(L){r.reverseOrbit||r.reverseHorizontalOrbit?f.theta+=L:f.theta-=L}function D(L){r.reverseOrbit||r.reverseVerticalOrbit?f.phi+=L:f.phi-=L}const B=(()=>{const L=new ae;return function(q,J){L.setFromMatrixColumn(J,0),L.multiplyScalar(-q),d.add(L)}})(),X=(()=>{const L=new ae;return function(q,J){r.screenSpacePanning===!0?L.setFromMatrixColumn(J,1):(L.setFromMatrixColumn(J,0),L.crossVectors(r.object.up,L)),L.multiplyScalar(q),d.add(L)}})(),Z=(()=>{const L=new ae;return function(q,J){const Ee=r.domElement;if(Ee&&r.object instanceof Et&&r.object.isPerspectiveCamera){const Xe=r.object.position;L.copy(Xe).sub(r.target);let at=L.length();at*=Math.tan(r.object.fov/2*Math.PI/180),B(2*q*at/Ee.clientHeight,r.object.matrix),X(2*J*at/Ee.clientHeight,r.object.matrix)}else Ee&&r.object instanceof $t&&r.object.isOrthographicCamera?(B(q*(r.object.right-r.object.left)/r.object.zoom/Ee.clientWidth,r.object.matrix),X(J*(r.object.top-r.object.bottom)/r.object.zoom/Ee.clientHeight,r.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),r.enablePan=!1)}})();function Q(L){r.object instanceof Et&&r.object.isPerspectiveCamera||r.object instanceof $t&&r.object.isOrthographicCamera?p=L:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),r.enableZoom=!1)}function _(L){Q(p/L)}function te(L){Q(p*L)}function ce(L){if(!r.zoomToCursor||!r.domElement)return;g=!0;const q=r.domElement.getBoundingClientRect(),J=L.clientX-q.left,Ee=L.clientY-q.top,Xe=q.width,at=q.height;y.x=J/Xe*2-1,y.y=-(Ee/at)*2+1,S.set(y.x,y.y,1).unproject(r.object).sub(r.object.position).normalize()}function R(L){return Math.max(r.minDistance,Math.min(r.maxDistance,L))}function pe(L){b.set(L.clientX,L.clientY)}function ye(L){ce(L),C.set(L.clientX,L.clientY)}function xe(L){T.set(L.clientX,L.clientY)}function Oe(L){x.set(L.clientX,L.clientY),v.subVectors(x,b).multiplyScalar(r.rotateSpeed);const q=r.domElement;q&&(F(2*Math.PI*v.x/q.clientHeight),D(2*Math.PI*v.y/q.clientHeight)),b.copy(x),r.update()}function G(L){P.set(L.clientX,L.clientY),h.subVectors(P,C),h.y>0?_(O()):h.y<0&&te(O()),C.copy(P),r.update()}function w(L){I.set(L.clientX,L.clientY),A.subVectors(I,T).multiplyScalar(r.panSpeed),Z(A.x,A.y),T.copy(I),r.update()}function M(L){ce(L),L.deltaY<0?te(O()):L.deltaY>0&&_(O()),r.update()}function N(L){let q=!1;switch(L.code){case r.keys.UP:Z(0,r.keyPanSpeed),q=!0;break;case r.keys.BOTTOM:Z(0,-r.keyPanSpeed),q=!0;break;case r.keys.LEFT:Z(r.keyPanSpeed,0),q=!0;break;case r.keys.RIGHT:Z(-r.keyPanSpeed,0),q=!0;break}q&&(L.preventDefault(),r.update())}function V(){if(m.length==1)b.set(m[0].pageX,m[0].pageY);else{const L=.5*(m[0].pageX+m[1].pageX),q=.5*(m[0].pageY+m[1].pageY);b.set(L,q)}}function U(){if(m.length==1)T.set(m[0].pageX,m[0].pageY);else{const L=.5*(m[0].pageX+m[1].pageX),q=.5*(m[0].pageY+m[1].pageY);T.set(L,q)}}function Y(){const L=m[0].pageX-m[1].pageX,q=m[0].pageY-m[1].pageY,J=Math.sqrt(L*L+q*q);C.set(0,J)}function ne(){r.enableZoom&&Y(),r.enablePan&&U()}function ve(){r.enableZoom&&Y(),r.enableRotate&&V()}function _e(L){if(m.length==1)x.set(L.pageX,L.pageY);else{const J=pt(L),Ee=.5*(L.pageX+J.x),Xe=.5*(L.pageY+J.y);x.set(Ee,Xe)}v.subVectors(x,b).multiplyScalar(r.rotateSpeed);const q=r.domElement;q&&(F(2*Math.PI*v.x/q.clientHeight),D(2*Math.PI*v.y/q.clientHeight)),b.copy(x)}function de(L){if(m.length==1)I.set(L.pageX,L.pageY);else{const q=pt(L),J=.5*(L.pageX+q.x),Ee=.5*(L.pageY+q.y);I.set(J,Ee)}A.subVectors(I,T).multiplyScalar(r.panSpeed),Z(A.x,A.y),T.copy(I)}function be(L){const q=pt(L),J=L.pageX-q.x,Ee=L.pageY-q.y,Xe=Math.sqrt(J*J+Ee*Ee);P.set(0,Xe),h.set(0,Math.pow(P.y/C.y,r.zoomSpeed)),_(h.y),C.copy(P)}function Ie(L){r.enableZoom&&be(L),r.enablePan&&de(L)}function Te(L){r.enableZoom&&be(L),r.enableRotate&&_e(L)}function Me(L){var q,J;r.enabled!==!1&&(m.length===0&&((q=r.domElement)==null||q.ownerDocument.addEventListener("pointermove",Ve),(J=r.domElement)==null||J.ownerDocument.addEventListener("pointerup",tt)),dt(L),L.pointerType==="touch"?ue(L):en(L))}function Ve(L){r.enabled!==!1&&(L.pointerType==="touch"?we(L):j(L))}function tt(L){var q,J,Ee;ot(L),m.length===0&&((q=r.domElement)==null||q.releasePointerCapture(L.pointerId),(J=r.domElement)==null||J.ownerDocument.removeEventListener("pointermove",Ve),(Ee=r.domElement)==null||Ee.ownerDocument.removeEventListener("pointerup",tt)),r.dispatchEvent(a),l=s.NONE}function en(L){let q;switch(L.button){case 0:q=r.mouseButtons.LEFT;break;case 1:q=r.mouseButtons.MIDDLE;break;case 2:q=r.mouseButtons.RIGHT;break;default:q=-1}switch(q){case yt.DOLLY:if(r.enableZoom===!1)return;ye(L),l=s.DOLLY;break;case yt.ROTATE:if(L.ctrlKey||L.metaKey||L.shiftKey){if(r.enablePan===!1)return;xe(L),l=s.PAN}else{if(r.enableRotate===!1)return;pe(L),l=s.ROTATE}break;case yt.PAN:if(L.ctrlKey||L.metaKey||L.shiftKey){if(r.enableRotate===!1)return;pe(L),l=s.ROTATE}else{if(r.enablePan===!1)return;xe(L),l=s.PAN}break;default:l=s.NONE}l!==s.NONE&&r.dispatchEvent(o)}function j(L){if(r.enabled!==!1)switch(l){case s.ROTATE:if(r.enableRotate===!1)return;Oe(L);break;case s.DOLLY:if(r.enableZoom===!1)return;G(L);break;case s.PAN:if(r.enablePan===!1)return;w(L);break}}function K(L){r.enabled===!1||r.enableZoom===!1||l!==s.NONE&&l!==s.ROTATE||(L.preventDefault(),r.dispatchEvent(o),M(L),r.dispatchEvent(a))}function oe(L){r.enabled===!1||r.enablePan===!1||N(L)}function ue(L){switch(bt(L),m.length){case 1:switch(r.touches.ONE){case _t.ROTATE:if(r.enableRotate===!1)return;V(),l=s.TOUCH_ROTATE;break;case _t.PAN:if(r.enablePan===!1)return;U(),l=s.TOUCH_PAN;break;default:l=s.NONE}break;case 2:switch(r.touches.TWO){case _t.DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;ne(),l=s.TOUCH_DOLLY_PAN;break;case _t.DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;ve(),l=s.TOUCH_DOLLY_ROTATE;break;default:l=s.NONE}break;default:l=s.NONE}l!==s.NONE&&r.dispatchEvent(o)}function we(L){switch(bt(L),l){case s.TOUCH_ROTATE:if(r.enableRotate===!1)return;_e(L),r.update();break;case s.TOUCH_PAN:if(r.enablePan===!1)return;de(L),r.update();break;case s.TOUCH_DOLLY_PAN:if(r.enableZoom===!1&&r.enablePan===!1)return;Ie(L),r.update();break;case s.TOUCH_DOLLY_ROTATE:if(r.enableZoom===!1&&r.enableRotate===!1)return;Te(L),r.update();break;default:l=s.NONE}}function He(L){r.enabled!==!1&&L.preventDefault()}function dt(L){m.push(L)}function ot(L){delete k[L.pointerId];for(let q=0;q{te(L),r.update()},this.dollyOut=(L=O())=>{_(L),r.update()},this.getScale=()=>p,this.setScale=L=>{Q(L),r.update()},this.getZoomScale=()=>O(),n!==void 0&&this.connect(n),this.update()}}new xt;new ae;new Jo;new ae;var _c=Object.defineProperty,Ac=(t,e,n)=>e in t?_c(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,di=(t,e,n)=>(Ac(t,typeof e!="symbol"?e+"":e,n),n);class Na{constructor(e){di(this,"data"),this.data=e}generateShapes(e,n=100,r){const i=[],o={letterSpacing:0,lineHeight:1,...r},a=Ec(e,n,this.data,o);for(let s=0,l=a.length;s #include #include uniform float thickness; @@ -423,15 +423,15 @@ var Ta=Object.defineProperty;var ka=(t,e,n)=>e in t?Ta(t,e,{enumerable:!0,config gl_FragColor = vec4(color, opacity); #include #include - }`);const Sc=["args","material-uniforms-color-value"];Fr.ReflectorShader;new se;new se;new se;var dr;/Mac/.test((dr=globalThis==null?void 0:globalThis.navigator)===null||dr===void 0?void 0:dr.platform);const Ic=["target","auto-rotate","auto-rotate-speed","enable-damping","damping-factor","enable-pan","key-pan-speed","keys","max-azimuth-angle","min-azimuth-angle","max-polar-angle","min-polar-angle","min-distance","max-distance","min-zoom","max-zoom","touches","enable-zoom","zoom-speed","enable-rotate","rotate-speed","mouse-buttons","args"],Rc=Fe({__name:"OrbitControls",props:{makeDefault:{type:Boolean,default:!1},camera:{},domElement:{},target:{default:()=>[0,0,0]},enableDamping:{type:Boolean,default:!0},dampingFactor:{default:.05},autoRotate:{type:Boolean,default:!1},autoRotateSpeed:{default:2},enablePan:{type:Boolean,default:!0},keyPanSpeed:{default:7},keys:{},maxAzimuthAngle:{default:Number.POSITIVE_INFINITY},minAzimuthAngle:{default:Number.NEGATIVE_INFINITY},maxPolarAngle:{default:Math.PI},minPolarAngle:{default:0},minDistance:{default:0},maxDistance:{default:Number.POSITIVE_INFINITY},minZoom:{default:0},maxZoom:{default:Number.POSITIVE_INFINITY},touches:{default:()=>({ONE:At.ROTATE,TWO:At.DOLLY_PAN})},enableZoom:{type:Boolean,default:!0},zoomSpeed:{default:1},enableRotate:{type:Boolean,default:!0},rotateSpeed:{default:1},mouseButtons:{default:()=>({LEFT:yt.ROTATE,MIDDLE:yt.DOLLY,RIGHT:yt.PAN})}},emits:["change","start","end"],setup(t,{expose:e,emit:n}){const r=t,i=n,{makeDefault:o,autoRotate:s,autoRotateSpeed:a,enableDamping:l,dampingFactor:u,enablePan:c,keyPanSpeed:f,maxAzimuthAngle:p,minAzimuthAngle:d,maxPolarAngle:b,minPolarAngle:x,minDistance:v,maxDistance:T,minZoom:I,maxZoom:_,enableZoom:C,zoomSpeed:P,enableRotate:h,touches:M,rotateSpeed:y,target:g,mouseButtons:m}=ei(r),{camera:k,renderer:E,extend:O,controls:z,invalidate:D}=Yn(),B=Wo(null);O({OrbitControls:kc}),je(B,Q=>{X(),Q&&o.value?z.value=Q:z.value=null});function X(){ar(B.value,"change",()=>{i("change",B.value),D()}),ar(B.value,"start",()=>i("start",B.value)),ar(B.value,"end",()=>i("end",B.value))}const{onBeforeRender:Z}=On();return Z(({invalidate:Q})=>{B.value&&(l.value||s.value)&&(B.value.update(),s.value&&Q())}),Ft(()=>{B.value&&B.value.dispose()}),e({instance:B}),(Q,A)=>(Q.camera||H(k))&&(Q.domElement||H(E))?(ee(),ie("TresOrbitControls",{key:0,ref_key:"controlsRef",ref:B,target:H(g),"auto-rotate":H(s),"auto-rotate-speed":H(a),"enable-damping":H(l),"damping-factor":H(u),"enable-pan":H(c),"key-pan-speed":H(f),keys:Q.keys,"max-azimuth-angle":H(p),"min-azimuth-angle":H(d),"max-polar-angle":H(b),"min-polar-angle":H(x),"min-distance":H(v),"max-distance":H(T),"min-zoom":H(I),"max-zoom":H(_),touches:H(M),"enable-zoom":H(C),"zoom-speed":H(P),"enable-rotate":H(h),"rotate-speed":H(y),"mouse-buttons":H(m),args:[Q.camera||H(k),Q.domElement||H(E).domElement]},null,8,Ic)):it("",!0)}});function Sn(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Wi={exports:{}},Xi;function Cc(){return Xi||(Xi=1,function(t,e){(function(n){t.exports=n()})(function(){return function n(r,i,o){function s(u,c){if(!i[u]){if(!r[u]){var f=typeof Sn=="function"&&Sn;if(!c&&f)return f(u,!0);if(a)return a(u,!0);throw new Error("Cannot find module '"+u+"'")}c=i[u]={exports:{}},r[u][0].call(c.exports,function(p){var d=r[u][1][p];return s(d||p)},c,c.exports,n,r,i,o)}return i[u].exports}for(var a=typeof Sn=="function"&&Sn,l=0;l[0,0,0]},enableDamping:{type:Boolean,default:!0},dampingFactor:{default:.05},autoRotate:{type:Boolean,default:!1},autoRotateSpeed:{default:2},enablePan:{type:Boolean,default:!0},keyPanSpeed:{default:7},keys:{},maxAzimuthAngle:{default:Number.POSITIVE_INFINITY},minAzimuthAngle:{default:Number.NEGATIVE_INFINITY},maxPolarAngle:{default:Math.PI},minPolarAngle:{default:0},minDistance:{default:0},maxDistance:{default:Number.POSITIVE_INFINITY},minZoom:{default:0},maxZoom:{default:Number.POSITIVE_INFINITY},touches:{default:()=>({ONE:_t.ROTATE,TWO:_t.DOLLY_PAN})},enableZoom:{type:Boolean,default:!0},zoomSpeed:{default:1},enableRotate:{type:Boolean,default:!0},rotateSpeed:{default:1},mouseButtons:{default:()=>({LEFT:yt.ROTATE,MIDDLE:yt.DOLLY,RIGHT:yt.PAN})}},emits:["change","start","end"],setup(t,{expose:e,emit:n}){const r=t,i=n,{makeDefault:o,autoRotate:a,autoRotateSpeed:s,enableDamping:l,dampingFactor:u,enablePan:c,keyPanSpeed:f,maxAzimuthAngle:p,minAzimuthAngle:d,maxPolarAngle:b,minPolarAngle:x,minDistance:v,maxDistance:T,minZoom:I,maxZoom:A,enableZoom:C,zoomSpeed:P,enableRotate:h,touches:S,rotateSpeed:y,target:g,mouseButtons:m}=ei(r),{camera:k,renderer:E,extend:O,controls:F,invalidate:D}=qn(),B=Wo(null);O({OrbitControls:kc}),je(B,Q=>{X(),Q&&o.value?F.value=Q:F.value=null});function X(){sr(B.value,"change",()=>{i("change",B.value),D()}),sr(B.value,"start",()=>i("start",B.value)),sr(B.value,"end",()=>i("end",B.value))}const{onBeforeRender:Z}=On();return Z(({invalidate:Q})=>{B.value&&(l.value||a.value)&&(B.value.update(),a.value&&Q())}),zt(()=>{B.value&&B.value.dispose()}),e({instance:B}),(Q,_)=>(Q.camera||H(k))&&(Q.domElement||H(E))?(ee(),ie("TresOrbitControls",{key:0,ref_key:"controlsRef",ref:B,target:H(g),"auto-rotate":H(a),"auto-rotate-speed":H(s),"enable-damping":H(l),"damping-factor":H(u),"enable-pan":H(c),"key-pan-speed":H(f),keys:Q.keys,"max-azimuth-angle":H(p),"min-azimuth-angle":H(d),"max-polar-angle":H(b),"min-polar-angle":H(x),"min-distance":H(v),"max-distance":H(T),"min-zoom":H(I),"max-zoom":H(A),touches:H(S),"enable-zoom":H(C),"zoom-speed":H(P),"enable-rotate":H(h),"rotate-speed":H(y),"mouse-buttons":H(m),args:[Q.camera||H(k),Q.domElement||H(E).domElement]},null,8,Ic)):it("",!0)}});function Sn(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Wi={exports:{}},Xi;function Cc(){return Xi||(Xi=1,function(t,e){(function(n){t.exports=n()})(function(){return function n(r,i,o){function a(u,c){if(!i[u]){if(!r[u]){var f=typeof Sn=="function"&&Sn;if(!c&&f)return f(u,!0);if(s)return s(u,!0);throw new Error("Cannot find module '"+u+"'")}c=i[u]={exports:{}},r[u][0].call(c.exports,function(p){var d=r[u][1][p];return a(d||p)},c,c.exports,n,r,i,o)}return i[u].exports}for(var s=typeof Sn=="function"&&Sn,l=0;l>16),D((65280&m)>>8),D(255&m);return k==2?D(255&(m=M(y.charAt(g))<<2|M(y.charAt(g+1))>>4)):k==1&&(D((m=M(y.charAt(g))<<10|M(y.charAt(g+1))<<4|M(y.charAt(g+2))>>2)>>8&255),D(255&m)),E},b.fromByteArray=function(y){var g,m,k,E,O=y.length%3,z="";function D(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(g=0,k=y.length-O;g>18&63)+D(E>>12&63)+D(E>>6&63)+D(63&E);switch(O){case 1:z=(z+=D((m=y[y.length-1])>>2))+D(m<<4&63)+"==";break;case 2:z=(z=(z+=D((m=(y[y.length-2]<<8)+y[y.length-1])>>10))+D(m>>4&63))+D(m<<2&63)+"="}return z}})(i===void 0?this.base64js={}:i)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(n,r,i){(function(o,s,v,l,u,c,f,p,d){var b=n("base64-js"),x=n("ieee754");function v(w,S,N){if(!(this instanceof v))return new v(w,S,N);var V,U,q,ne,ve=typeof w;if(S==="base64"&&ve=="string")for(w=(ne=w).trim?ne.trim():ne.replace(/^\s+|\s+$/g,"");w.length%4!=0;)w+="=";if(ve=="number")V=Z(w);else if(ve=="string")V=v.byteLength(w,S);else{if(ve!="object")throw new Error("First argument needs to be a number, array or string.");V=Z(w.length)}if(v._useTypedArrays?U=v._augment(new Uint8Array(V)):((U=this).length=V,U._isBuffer=!0),v._useTypedArrays&&typeof w.byteLength=="number")U._set(w);else if(Q(ne=w)||v.isBuffer(ne)||ne&&typeof ne=="object"&&typeof ne.length=="number")for(q=0;q>8,ne=ne%256,ve.push(ne),ve.push(q);return ve}(S),w,N,V)}function _(w,S,N){var V="";N=Math.min(w.length,N);for(var U=S;U>>0)):(S+1>>0),U}function h(w,S,N,V){if(V||(G(typeof N=="boolean","missing or invalid endian"),G(S!=null,"missing offset"),G(S+1>>8*(V?q:1-q)}function k(w,S,N,V,U){if(U||(G(S!=null,"missing value"),G(typeof V=="boolean","missing or invalid endian"),G(N!=null,"missing offset"),G(N+3>>8*(V?q:3-q)&255}function E(w,S,N,V,U){U||(G(S!=null,"missing value"),G(typeof V=="boolean","missing or invalid endian"),G(N!=null,"missing offset"),G(N+1this.length&&(V=this.length);var U=(V=w.length-S=this.length))return this[w]},v.prototype.readUInt16LE=function(w,S){return C(this,w,!0,S)},v.prototype.readUInt16BE=function(w,S){return C(this,w,!1,S)},v.prototype.readUInt32LE=function(w,S){return P(this,w,!0,S)},v.prototype.readUInt32BE=function(w,S){return P(this,w,!1,S)},v.prototype.readInt8=function(w,S){if(S||(G(w!=null,"missing offset"),G(w=this.length))return 128&this[w]?-1*(255-this[w]+1):this[w]},v.prototype.readInt16LE=function(w,S){return h(this,w,!0,S)},v.prototype.readInt16BE=function(w,S){return h(this,w,!1,S)},v.prototype.readInt32LE=function(w,S){return M(this,w,!0,S)},v.prototype.readInt32BE=function(w,S){return M(this,w,!1,S)},v.prototype.readFloatLE=function(w,S){return y(this,w,!0,S)},v.prototype.readFloatBE=function(w,S){return y(this,w,!1,S)},v.prototype.readDoubleLE=function(w,S){return g(this,w,!0,S)},v.prototype.readDoubleBE=function(w,S){return g(this,w,!1,S)},v.prototype.writeUInt8=function(w,S,N){N||(G(w!=null,"missing value"),G(S!=null,"missing offset"),G(S=this.length||(this[S]=w)},v.prototype.writeUInt16LE=function(w,S,N){m(this,w,S,!0,N)},v.prototype.writeUInt16BE=function(w,S,N){m(this,w,S,!1,N)},v.prototype.writeUInt32LE=function(w,S,N){k(this,w,S,!0,N)},v.prototype.writeUInt32BE=function(w,S,N){k(this,w,S,!1,N)},v.prototype.writeInt8=function(w,S,N){N||(G(w!=null,"missing value"),G(S!=null,"missing offset"),G(S=this.length||(0<=w?this.writeUInt8(w,S,N):this.writeUInt8(255+w+1,S,N))},v.prototype.writeInt16LE=function(w,S,N){E(this,w,S,!0,N)},v.prototype.writeInt16BE=function(w,S,N){E(this,w,S,!1,N)},v.prototype.writeInt32LE=function(w,S,N){O(this,w,S,!0,N)},v.prototype.writeInt32BE=function(w,S,N){O(this,w,S,!1,N)},v.prototype.writeFloatLE=function(w,S,N){z(this,w,S,!0,N)},v.prototype.writeFloatBE=function(w,S,N){z(this,w,S,!1,N)},v.prototype.writeDoubleLE=function(w,S,N){D(this,w,S,!0,N)},v.prototype.writeDoubleBE=function(w,S,N){D(this,w,S,!1,N)},v.prototype.fill=function(w,S,N){if(S=S||0,N=N||this.length,G(typeof(w=typeof(w=w||0)=="string"?w.charCodeAt(0):w)=="number"&&!isNaN(w),"value is not a number"),G(S<=N,"end < start"),N!==S&&this.length!==0){G(0<=S&&S"},v.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(v._useTypedArrays)return new v(this).buffer;for(var w=new Uint8Array(this.length),S=0,N=w.length;S=S.length||U>=w.length);U++)S[U+N]=w[U];return U}function pe(w){try{return decodeURIComponent(w)}catch{return"�"}}function ye(w,S){G(typeof w=="number","cannot write a non-number as a number"),G(0<=w,"specified a negative value for writing an unsigned value"),G(w<=S,"value is larger than maximum value for type"),G(Math.floor(w)===w,"value has a fractional component")}function xe(w,S,N){G(typeof w=="number","cannot write a non-number as a number"),G(w<=S,"value larger than maximum allowed value"),G(N<=w,"value smaller than minimum allowed value"),G(Math.floor(w)===w,"value has a fractional component")}function Oe(w,S,N){G(typeof w=="number","cannot write a non-number as a number"),G(w<=S,"value larger than maximum allowed value"),G(N<=w,"value smaller than minimum allowed value")}function G(w,S){if(!w)throw new Error(S||"Failed assertion")}v._augment=function(w){return w._isBuffer=!0,w._get=w.get,w._set=w.set,w.get=B.get,w.set=B.set,w.write=B.write,w.toString=B.toString,w.toLocaleString=B.toString,w.toJSON=B.toJSON,w.copy=B.copy,w.slice=B.slice,w.readUInt8=B.readUInt8,w.readUInt16LE=B.readUInt16LE,w.readUInt16BE=B.readUInt16BE,w.readUInt32LE=B.readUInt32LE,w.readUInt32BE=B.readUInt32BE,w.readInt8=B.readInt8,w.readInt16LE=B.readInt16LE,w.readInt16BE=B.readInt16BE,w.readInt32LE=B.readInt32LE,w.readInt32BE=B.readInt32BE,w.readFloatLE=B.readFloatLE,w.readFloatBE=B.readFloatBE,w.readDoubleLE=B.readDoubleLE,w.readDoubleBE=B.readDoubleBE,w.writeUInt8=B.writeUInt8,w.writeUInt16LE=B.writeUInt16LE,w.writeUInt16BE=B.writeUInt16BE,w.writeUInt32LE=B.writeUInt32LE,w.writeUInt32BE=B.writeUInt32BE,w.writeInt8=B.writeInt8,w.writeInt16LE=B.writeInt16LE,w.writeInt16BE=B.writeInt16BE,w.writeInt32LE=B.writeInt32LE,w.writeInt32BE=B.writeInt32BE,w.writeFloatLE=B.writeFloatLE,w.writeFloatBE=B.writeFloatBE,w.writeDoubleLE=B.writeDoubleLE,w.writeDoubleBE=B.writeDoubleBE,w.fill=B.fill,w.inspect=B.inspect,w.toArrayBuffer=B.toArrayBuffer,w}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(n,r,i){(function(o,s,b,l,u,c,f,p,d){var b=n("buffer").Buffer,x=4,v=new b(x);v.fill(0),r.exports={hash:function(T,I,_,C){for(var P=I(function(m,k){m.length%x!=0&&(E=m.length+(x-m.length%x),m=b.concat([m,v],E));for(var E,O=[],z=k?m.readInt32BE:m.readInt32LE,D=0;D_?X=B(X):X.length<_&&(X=b.concat([X,C],_));for(var Q=new b(_),A=new b(_),te=0;te<_;te++)Q[te]=54^X[te],A[te]=92^X[te];return Z=B(b.concat([Q,Z])),B(b.concat([A,Z]))}(E,k,D):E(D);return O=null,z?D.toString(z):D}}}function h(){var m=[].slice.call(arguments).join(" ");throw new Error([m,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(` -`))}C.fill(0),i.createHash=function(m){return P(m)},i.createHmac=P,i.randomBytes=function(m,k){if(!k||!k.call)return new b(T(m));try{k.call(this,void 0,new b(T(m)))}catch(E){k(E)}};var M,y=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],g=function(m){i[m]=function(){h("sorry,",m,"is not implemented yet")}};for(M in y)g(y[M])}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(n,r,i){(function(o,s,a,l,u,c,f,p,d){var b=n("./helpers");function x(h,M){h[M>>5]|=128<>>9<<4)]=M;for(var y=1732584193,g=-271733879,m=-1732584194,k=271733878,E=0;E>>32-m,y)}function T(h,M,y,g,m,k,E){return v(M&y|~M&g,h,M,m,k,E)}function I(h,M,y,g,m,k,E){return v(M&g|y&~g,h,M,m,k,E)}function _(h,M,y,g,m,k,E){return v(M^y^g,h,M,m,k,E)}function C(h,M,y,g,m,k,E){return v(y^(M|~g),h,M,m,k,E)}function P(h,M){var y=(65535&h)+(65535&M);return(h>>16)+(M>>16)+(y>>16)<<16|65535&y}r.exports=function(h){return b.hash(h,x,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(n,r,i){(function(o,s,a,l,u,c,f,p,d){r.exports=function(b){for(var x,v=new Array(b),T=0;T>>((3&T)<<3)&255;return v}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(n,r,i){(function(o,s,a,l,u,c,f,p,d){var b=n("./helpers");function x(I,_){I[_>>5]|=128<<24-_%32,I[15+(_+64>>9<<4)]=_;for(var C,P,h,M=Array(80),y=1732584193,g=-271733879,m=-1732584194,k=271733878,E=-1009589776,O=0;O>16)+(_>>16)+(C>>16)<<16|65535&C}function T(I,_){return I<<_|I>>>32-_}r.exports=function(I){return b.hash(I,x,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(n,r,i){(function(o,s,a,l,u,c,f,p,d){function b(_,C){var P=(65535&_)+(65535&C);return(_>>16)+(C>>16)+(P>>16)<<16|65535&P}function x(_,C){var P,h=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),M=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),y=new Array(64);_[C>>5]|=128<<24-C%32,_[15+(C+64>>9<<4)]=C;for(var g,m,k=0;k<_.length;k+=16){for(var E=M[0],O=M[1],z=M[2],D=M[3],B=M[4],X=M[5],Z=M[6],Q=M[7],A=0;A<64;A++)y[A]=A<16?_[A+k]:b(b(b((m=y[A-2],T(m,17)^T(m,19)^I(m,10)),y[A-7]),(m=y[A-15],T(m,7)^T(m,18)^I(m,3))),y[A-16]),P=b(b(b(b(Q,T(m=B,6)^T(m,11)^T(m,25)),B&X^~B&Z),h[A]),y[A]),g=b(T(g=E,2)^T(g,13)^T(g,22),E&O^E&z^O&z),Q=Z,Z=X,X=B,B=b(D,P),D=z,z=O,O=E,E=b(P,g);M[0]=b(E,M[0]),M[1]=b(O,M[1]),M[2]=b(z,M[2]),M[3]=b(D,M[3]),M[4]=b(B,M[4]),M[5]=b(X,M[5]),M[6]=b(Z,M[6]),M[7]=b(Q,M[7])}return M}var v=n("./helpers"),T=function(_,C){return _>>>C|_<<32-C},I=function(_,C){return _>>>C};r.exports=function(_){return v.hash(_,x,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(n,r,i){(function(o,s,a,l,u,c,f,p,d){i.read=function(b,x,v,T,k){var _,C,P=8*k-T-1,h=(1<>1,y=-7,g=v?k-1:0,m=v?-1:1,k=b[x+g];for(g+=m,_=k&(1<<-y)-1,k>>=-y,y+=P;0>=-y,y+=T;0>1,g=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,m=T?0:E-1,k=T?1:-1,E=x<0||x===0&&1/x<0?1:0;for(x=Math.abs(x),isNaN(x)||x===1/0?(P=isNaN(x)?1:0,C=M):(C=Math.floor(Math.log(x)/Math.LN2),x*(T=Math.pow(2,-C))<1&&(C--,T*=2),2<=(x+=1<=C+y?g/T:g*Math.pow(2,1-y))*T&&(C++,T/=2),M<=C+y?(P=0,C=M):1<=C+y?(P=(x*T-1)*Math.pow(2,I),C+=y):(P=x*Math.pow(2,y-1)*Math.pow(2,I),C=0));8<=I;b[v+m]=255&P,m+=k,P/=256,I-=8);for(C=C<>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]),Ji}var to,no;function Ps(){return no||(no=1,to=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]),to}var pr,ro;function Lc(){if(ro)return pr;ro=1;var t=Ls();return pr=t.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),pr}var hr,io;function Pc(){if(io)return hr;io=1;var t=Ps();return t=t.slice().filter(function(e){return!/^(gl\_|texture)/.test(e)}),hr=t.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"]),hr}var mr,oo;function Dc(){if(oo)return mr;oo=1,mr=C;var t=Ls(),e=Nc(),n=Ps(),r=Lc(),i=Pc(),o=999,s=9999,a=0,l=1,u=2,c=3,f=4,p=5,d=6,b=7,x=8,v=9,T=10,I=11,_=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];function C(P){var h=0,M=0,y=o,g,m,k=[],E=[],O=1,z=0,D=0,B=!1,X=!1,Z="",Q;P=P||{};var A=n,te=t;P.version==="300 es"&&(A=i,te=r);for(var ce={},R={},h=0;h0)continue;Te=de.slice(0,1).join("")}return pe(Te),D+=Te.length,k=k.slice(Te.length),k.length}while(!0)}function q(){return/[^a-fA-F0-9]/.test(g)?(pe(k.join("")),y=o,h):(k.push(g),m=g,h+1)}function ne(){return g==="."||/[eE]/.test(g)?(k.push(g),y=p,m=g,h+1):g==="x"&&k.length===1&&k[0]==="0"?(y=I,k.push(g),m=g,h+1):/[^\d]/.test(g)?(pe(k.join("")),y=o,h):(k.push(g),m=g,h+1)}function ve(){return g==="f"&&(k.push(g),m=g,h+=1),/[eE]/.test(g)||(g==="-"||g==="+")&&/[eE]/.test(m)?(k.push(g),m=g,h+1):/[^\d]/.test(g)?(pe(k.join("")),y=o,h):(k.push(g),m=g,h+1)}function Ae(){if(/[^\d\w_]/.test(g)){var de=k.join("");return R[de]?y=x:ce[de]?y=b:y=d,pe(k.join("")),y=o,h}return k.push(g),m=g,h+1}}return mr}var gr,so;function Oc(){if(so)return gr;so=1;var t=Dc();gr=e;function e(n,r){var i=t(r),o=[];return o=o.concat(i(n)),o=o.concat(i(null)),o}return gr}Oc();function Fc(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function zc(t){var e=Fc(t,"string");return typeof e=="symbol"?e:String(e)}function Se(t,e,n){return e=zc(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var le={position:"csm_Position",positionRaw:"csm_PositionRaw",pointSize:"csm_PointSize",fragColor:"csm_FragColor",diffuseColor:"csm_DiffuseColor",normal:"csm_Normal",roughness:"csm_Roughness",metalness:"csm_Metalness",emissive:"csm_Emissive",ao:"csm_AO",bump:"csm_Bump",depthAlpha:"csm_DepthAlpha"},Ge,Ut;Ge={},Se(Ge,"".concat(le.normal),{"#include ":` +`)},_domwindow:function(){return g("domwindow")},_bigint:function(m){return g("bigint:"+m.toString())},_process:function(){return g("process")},_timer:function(){return g("timer")},_pipe:function(){return g("pipe")},_tcp:function(){return g("tcp")},_udp:function(){return g("udp")},_tty:function(){return g("tty")},_statwatcher:function(){return g("statwatcher")},_securecontext:function(){return g("securecontext")},_connection:function(){return g("connection")},_zlib:function(){return g("zlib")},_context:function(){return g("context")},_nodescript:function(){return g("nodescript")},_httpparser:function(){return g("httpparser")},_dataview:function(){return g("dataview")},_signal:function(){return g("signal")},_fsevent:function(){return g("fsevent")},_tlswrap:function(){return g("tlswrap")}}}function P(){return{buf:"",write:function(h){this.buf+=h},end:function(h){this.buf+=h},read:function(){return this.buf}}}i.writeToStream=function(h,S,y){return y===void 0&&(y=S,S={}),C(S=I(h,S),y).dispatch(h)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,r,i){(function(o,a,s,l,u,c,f,p,d){(function(b){var x=typeof Uint8Array<"u"?Uint8Array:Array,v=43,T=47,I=48,A=97,C=65,P=45,h=95;function S(y){return y=y.charCodeAt(0),y===v||y===P?62:y===T||y===h?63:y>16),D((65280&m)>>8),D(255&m);return k==2?D(255&(m=S(y.charAt(g))<<2|S(y.charAt(g+1))>>4)):k==1&&(D((m=S(y.charAt(g))<<10|S(y.charAt(g+1))<<4|S(y.charAt(g+2))>>2)>>8&255),D(255&m)),E},b.fromByteArray=function(y){var g,m,k,E,O=y.length%3,F="";function D(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(g=0,k=y.length-O;g>18&63)+D(E>>12&63)+D(E>>6&63)+D(63&E);switch(O){case 1:F=(F+=D((m=y[y.length-1])>>2))+D(m<<4&63)+"==";break;case 2:F=(F=(F+=D((m=(y[y.length-2]<<8)+y[y.length-1])>>10))+D(m>>4&63))+D(m<<2&63)+"="}return F}})(i===void 0?this.base64js={}:i)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(n,r,i){(function(o,a,v,l,u,c,f,p,d){var b=n("base64-js"),x=n("ieee754");function v(w,M,N){if(!(this instanceof v))return new v(w,M,N);var V,U,Y,ne,ve=typeof w;if(M==="base64"&&ve=="string")for(w=(ne=w).trim?ne.trim():ne.replace(/^\s+|\s+$/g,"");w.length%4!=0;)w+="=";if(ve=="number")V=Z(w);else if(ve=="string")V=v.byteLength(w,M);else{if(ve!="object")throw new Error("First argument needs to be a number, array or string.");V=Z(w.length)}if(v._useTypedArrays?U=v._augment(new Uint8Array(V)):((U=this).length=V,U._isBuffer=!0),v._useTypedArrays&&typeof w.byteLength=="number")U._set(w);else if(Q(ne=w)||v.isBuffer(ne)||ne&&typeof ne=="object"&&typeof ne.length=="number")for(Y=0;Y>8,ne=ne%256,ve.push(ne),ve.push(Y);return ve}(M),w,N,V)}function A(w,M,N){var V="";N=Math.min(w.length,N);for(var U=M;U>>0)):(M+1>>0),U}function h(w,M,N,V){if(V||(G(typeof N=="boolean","missing or invalid endian"),G(M!=null,"missing offset"),G(M+1>>8*(V?Y:1-Y)}function k(w,M,N,V,U){if(U||(G(M!=null,"missing value"),G(typeof V=="boolean","missing or invalid endian"),G(N!=null,"missing offset"),G(N+3>>8*(V?Y:3-Y)&255}function E(w,M,N,V,U){U||(G(M!=null,"missing value"),G(typeof V=="boolean","missing or invalid endian"),G(N!=null,"missing offset"),G(N+1this.length&&(V=this.length);var U=(V=w.length-M=this.length))return this[w]},v.prototype.readUInt16LE=function(w,M){return C(this,w,!0,M)},v.prototype.readUInt16BE=function(w,M){return C(this,w,!1,M)},v.prototype.readUInt32LE=function(w,M){return P(this,w,!0,M)},v.prototype.readUInt32BE=function(w,M){return P(this,w,!1,M)},v.prototype.readInt8=function(w,M){if(M||(G(w!=null,"missing offset"),G(w=this.length))return 128&this[w]?-1*(255-this[w]+1):this[w]},v.prototype.readInt16LE=function(w,M){return h(this,w,!0,M)},v.prototype.readInt16BE=function(w,M){return h(this,w,!1,M)},v.prototype.readInt32LE=function(w,M){return S(this,w,!0,M)},v.prototype.readInt32BE=function(w,M){return S(this,w,!1,M)},v.prototype.readFloatLE=function(w,M){return y(this,w,!0,M)},v.prototype.readFloatBE=function(w,M){return y(this,w,!1,M)},v.prototype.readDoubleLE=function(w,M){return g(this,w,!0,M)},v.prototype.readDoubleBE=function(w,M){return g(this,w,!1,M)},v.prototype.writeUInt8=function(w,M,N){N||(G(w!=null,"missing value"),G(M!=null,"missing offset"),G(M=this.length||(this[M]=w)},v.prototype.writeUInt16LE=function(w,M,N){m(this,w,M,!0,N)},v.prototype.writeUInt16BE=function(w,M,N){m(this,w,M,!1,N)},v.prototype.writeUInt32LE=function(w,M,N){k(this,w,M,!0,N)},v.prototype.writeUInt32BE=function(w,M,N){k(this,w,M,!1,N)},v.prototype.writeInt8=function(w,M,N){N||(G(w!=null,"missing value"),G(M!=null,"missing offset"),G(M=this.length||(0<=w?this.writeUInt8(w,M,N):this.writeUInt8(255+w+1,M,N))},v.prototype.writeInt16LE=function(w,M,N){E(this,w,M,!0,N)},v.prototype.writeInt16BE=function(w,M,N){E(this,w,M,!1,N)},v.prototype.writeInt32LE=function(w,M,N){O(this,w,M,!0,N)},v.prototype.writeInt32BE=function(w,M,N){O(this,w,M,!1,N)},v.prototype.writeFloatLE=function(w,M,N){F(this,w,M,!0,N)},v.prototype.writeFloatBE=function(w,M,N){F(this,w,M,!1,N)},v.prototype.writeDoubleLE=function(w,M,N){D(this,w,M,!0,N)},v.prototype.writeDoubleBE=function(w,M,N){D(this,w,M,!1,N)},v.prototype.fill=function(w,M,N){if(M=M||0,N=N||this.length,G(typeof(w=typeof(w=w||0)=="string"?w.charCodeAt(0):w)=="number"&&!isNaN(w),"value is not a number"),G(M<=N,"end < start"),N!==M&&this.length!==0){G(0<=M&&M"},v.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(v._useTypedArrays)return new v(this).buffer;for(var w=new Uint8Array(this.length),M=0,N=w.length;M=M.length||U>=w.length);U++)M[U+N]=w[U];return U}function pe(w){try{return decodeURIComponent(w)}catch{return"�"}}function ye(w,M){G(typeof w=="number","cannot write a non-number as a number"),G(0<=w,"specified a negative value for writing an unsigned value"),G(w<=M,"value is larger than maximum value for type"),G(Math.floor(w)===w,"value has a fractional component")}function xe(w,M,N){G(typeof w=="number","cannot write a non-number as a number"),G(w<=M,"value larger than maximum allowed value"),G(N<=w,"value smaller than minimum allowed value"),G(Math.floor(w)===w,"value has a fractional component")}function Oe(w,M,N){G(typeof w=="number","cannot write a non-number as a number"),G(w<=M,"value larger than maximum allowed value"),G(N<=w,"value smaller than minimum allowed value")}function G(w,M){if(!w)throw new Error(M||"Failed assertion")}v._augment=function(w){return w._isBuffer=!0,w._get=w.get,w._set=w.set,w.get=B.get,w.set=B.set,w.write=B.write,w.toString=B.toString,w.toLocaleString=B.toString,w.toJSON=B.toJSON,w.copy=B.copy,w.slice=B.slice,w.readUInt8=B.readUInt8,w.readUInt16LE=B.readUInt16LE,w.readUInt16BE=B.readUInt16BE,w.readUInt32LE=B.readUInt32LE,w.readUInt32BE=B.readUInt32BE,w.readInt8=B.readInt8,w.readInt16LE=B.readInt16LE,w.readInt16BE=B.readInt16BE,w.readInt32LE=B.readInt32LE,w.readInt32BE=B.readInt32BE,w.readFloatLE=B.readFloatLE,w.readFloatBE=B.readFloatBE,w.readDoubleLE=B.readDoubleLE,w.readDoubleBE=B.readDoubleBE,w.writeUInt8=B.writeUInt8,w.writeUInt16LE=B.writeUInt16LE,w.writeUInt16BE=B.writeUInt16BE,w.writeUInt32LE=B.writeUInt32LE,w.writeUInt32BE=B.writeUInt32BE,w.writeInt8=B.writeInt8,w.writeInt16LE=B.writeInt16LE,w.writeInt16BE=B.writeInt16BE,w.writeInt32LE=B.writeInt32LE,w.writeInt32BE=B.writeInt32BE,w.writeFloatLE=B.writeFloatLE,w.writeFloatBE=B.writeFloatBE,w.writeDoubleLE=B.writeDoubleLE,w.writeDoubleBE=B.writeDoubleBE,w.fill=B.fill,w.inspect=B.inspect,w.toArrayBuffer=B.toArrayBuffer,w}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(n,r,i){(function(o,a,b,l,u,c,f,p,d){var b=n("buffer").Buffer,x=4,v=new b(x);v.fill(0),r.exports={hash:function(T,I,A,C){for(var P=I(function(m,k){m.length%x!=0&&(E=m.length+(x-m.length%x),m=b.concat([m,v],E));for(var E,O=[],F=k?m.readInt32BE:m.readInt32LE,D=0;DA?X=B(X):X.length>5]|=128<>>9<<4)]=S;for(var y=1732584193,g=-271733879,m=-1732584194,k=271733878,E=0;E>>32-m,y)}function T(h,S,y,g,m,k,E){return v(S&y|~S&g,h,S,m,k,E)}function I(h,S,y,g,m,k,E){return v(S&g|y&~g,h,S,m,k,E)}function A(h,S,y,g,m,k,E){return v(S^y^g,h,S,m,k,E)}function C(h,S,y,g,m,k,E){return v(y^(S|~g),h,S,m,k,E)}function P(h,S){var y=(65535&h)+(65535&S);return(h>>16)+(S>>16)+(y>>16)<<16|65535&y}r.exports=function(h){return b.hash(h,x,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(n,r,i){(function(o,a,s,l,u,c,f,p,d){r.exports=function(b){for(var x,v=new Array(b),T=0;T>>((3&T)<<3)&255;return v}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(n,r,i){(function(o,a,s,l,u,c,f,p,d){var b=n("./helpers");function x(I,A){I[A>>5]|=128<<24-A%32,I[15+(A+64>>9<<4)]=A;for(var C,P,h,S=Array(80),y=1732584193,g=-271733879,m=-1732584194,k=271733878,E=-1009589776,O=0;O>16)+(A>>16)+(C>>16)<<16|65535&C}function T(I,A){return I<>>32-A}r.exports=function(I){return b.hash(I,x,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(n,r,i){(function(o,a,s,l,u,c,f,p,d){function b(A,C){var P=(65535&A)+(65535&C);return(A>>16)+(C>>16)+(P>>16)<<16|65535&P}function x(A,C){var P,h=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),S=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),y=new Array(64);A[C>>5]|=128<<24-C%32,A[15+(C+64>>9<<4)]=C;for(var g,m,k=0;k>>C|A<<32-C},I=function(A,C){return A>>>C};r.exports=function(A){return v.hash(A,x,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(n,r,i){(function(o,a,s,l,u,c,f,p,d){i.read=function(b,x,v,T,k){var A,C,P=8*k-T-1,h=(1<>1,y=-7,g=v?k-1:0,m=v?-1:1,k=b[x+g];for(g+=m,A=k&(1<<-y)-1,k>>=-y,y+=P;0>=-y,y+=T;0>1,g=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,m=T?0:E-1,k=T?1:-1,E=x<0||x===0&&1/x<0?1:0;for(x=Math.abs(x),isNaN(x)||x===1/0?(P=isNaN(x)?1:0,C=S):(C=Math.floor(Math.log(x)/Math.LN2),x*(T=Math.pow(2,-C))<1&&(C--,T*=2),2<=(x+=1<=C+y?g/T:g*Math.pow(2,1-y))*T&&(C++,T/=2),S<=C+y?(P=0,C=S):1<=C+y?(P=(x*T-1)*Math.pow(2,I),C+=y):(P=x*Math.pow(2,y-1)*Math.pow(2,I),C=0));8<=I;b[v+m]=255&P,m+=k,P/=256,I-=8);for(C=C<>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]),Ji}var to,no;function Pa(){return no||(no=1,to=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]),to}var pr,ro;function Lc(){if(ro)return pr;ro=1;var t=La();return pr=t.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"]),pr}var hr,io;function Pc(){if(io)return hr;io=1;var t=Pa();return t=t.slice().filter(function(e){return!/^(gl\_|texture)/.test(e)}),hr=t.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"]),hr}var mr,oo;function Dc(){if(oo)return mr;oo=1,mr=C;var t=La(),e=Nc(),n=Pa(),r=Lc(),i=Pc(),o=999,a=9999,s=0,l=1,u=2,c=3,f=4,p=5,d=6,b=7,x=8,v=9,T=10,I=11,A=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"];function C(P){var h=0,S=0,y=o,g,m,k=[],E=[],O=1,F=0,D=0,B=!1,X=!1,Z="",Q;P=P||{};var _=n,te=t;P.version==="300 es"&&(_=i,te=r);for(var ce={},R={},h=0;h<_.length;h++)ce[_[h]]=!0;for(var h=0;h0)continue;Te=de.slice(0,1).join("")}return pe(Te),D+=Te.length,k=k.slice(Te.length),k.length}while(!0)}function Y(){return/[^a-fA-F0-9]/.test(g)?(pe(k.join("")),y=o,h):(k.push(g),m=g,h+1)}function ne(){return g==="."||/[eE]/.test(g)?(k.push(g),y=p,m=g,h+1):g==="x"&&k.length===1&&k[0]==="0"?(y=I,k.push(g),m=g,h+1):/[^\d]/.test(g)?(pe(k.join("")),y=o,h):(k.push(g),m=g,h+1)}function ve(){return g==="f"&&(k.push(g),m=g,h+=1),/[eE]/.test(g)||(g==="-"||g==="+")&&/[eE]/.test(m)?(k.push(g),m=g,h+1):/[^\d]/.test(g)?(pe(k.join("")),y=o,h):(k.push(g),m=g,h+1)}function _e(){if(/[^\d\w_]/.test(g)){var de=k.join("");return R[de]?y=x:ce[de]?y=b:y=d,pe(k.join("")),y=o,h}return k.push(g),m=g,h+1}}return mr}var gr,ao;function Oc(){if(ao)return gr;ao=1;var t=Dc();gr=e;function e(n,r){var i=t(r),o=[];return o=o.concat(i(n)),o=o.concat(i(null)),o}return gr}Oc();function zc(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}function Fc(t){var e=zc(t,"string");return typeof e=="symbol"?e:String(e)}function Se(t,e,n){return e=Fc(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var le={position:"csm_Position",positionRaw:"csm_PositionRaw",pointSize:"csm_PointSize",fragColor:"csm_FragColor",diffuseColor:"csm_DiffuseColor",normal:"csm_Normal",roughness:"csm_Roughness",metalness:"csm_Metalness",emissive:"csm_Emissive",ao:"csm_AO",bump:"csm_Bump",depthAlpha:"csm_DepthAlpha"},Ge,Ut;Ge={},Se(Ge,"".concat(le.normal),{"#include ":` vec3 objectNormal = `.concat(le.normal,`; #ifdef USE_TANGENT vec3 objectTangent = vec3( tangent.xyz ); @@ -511,7 +511,7 @@ void main() { mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; -}`;const vn=new se(0,0,0),pi=new se(0,0,0),jc=new se(0,0,0);function ao(t,e,n){const r=vn.setFromMatrixPosition(t.matrixWorld);r.project(e);const i=n.width/2,o=n.height/2;return[(Number.isNaN(r.x)?0:r.x)*i+i,-(r.y*o)+o,r.z]}function Vc(t,e){const n=vn.setFromMatrixPosition(t.matrixWorld),r=pi.setFromMatrixPosition(e.matrixWorld),i=n.sub(r),o=e.getWorldDirection(jc);return i.angleTo(o)>Math.PI/2}function Hc(t,e,n,r){const i=vn.setFromMatrixPosition(t.matrixWorld),o=i.clone();o.project(e),n.setFromCamera(new Pe(o.x,o.y),e);const s=n.intersectObjects(r,!0);if(s.length>0){const a=s[0].distance;return i.distanceTo(n.ray.origin)Math.abs(t)<1e-10?0:t;function Ds(t,e,n=""){let r="matrix3d(";for(let i=0;i!==16;i++)r+=Br(e[i]*t.elements[i])+(i!==15?",":")");return n+r}const Yc=(t=>e=>Ds(e,t))([1,-1,1,1,1,-1,1,1,1,-1,1,1,1,-1,1,1]),qc=(t=>(e,n)=>Ds(e,t(n),"translate(-50%,-50%)"))(t=>[1/t,1/t,1/t,1,-1/t,-1/t,-1/t,-1,1/t,1/t,1/t,1,1,1,1,1]),Kc=["geometry","material"];new ts;var Ur={exports:{}},Wc=Ur.exports,lo;function Xc(){return lo||(lo=1,function(t,e){(function(n,r){t.exports=r()})(Wc,function(){var n=function(){function r(d){return s.appendChild(d.dom),d}function i(d){for(var b=0;bl+1e3&&(c.update(1e3*u/(d-l),100),l=d,u=0,p)){var b=performance.memory;p.update(b.usedJSHeapSize/1048576,b.jsHeapSizeLimit/1048576)}return d},update:function(){a=this.end()},domElement:s,setMode:i}};return n.Panel=function(r,i,o){var s=1/0,a=0,l=Math.round,u=l(window.devicePixelRatio||1),c=80*u,f=48*u,p=3*u,d=2*u,b=3*u,x=15*u,v=74*u,T=30*u,I=document.createElement("canvas");I.width=c,I.height=f,I.style.cssText="width:80px;height:48px";var _=I.getContext("2d");return _.font="bold "+9*u+"px Helvetica,Arial,sans-serif",_.textBaseline="top",_.fillStyle=o,_.fillRect(0,0,c,f),_.fillStyle=i,_.fillText(r,p,d),_.fillRect(b,x,v,T),_.fillStyle=o,_.globalAlpha=.9,_.fillRect(b,x,v,T),{dom:I,update:function(C,P){s=Math.min(s,C),a=Math.max(a,C),_.fillStyle=o,_.globalAlpha=1,_.fillRect(0,0,c,x),_.fillStyle=i,_.fillText(l(C)+" "+r+" ("+l(s)+"-"+l(a)+")",p,d),_.drawImage(I,b+u,x,v-u,T,b,x,v-u,T),_.fillRect(b+v-u,x,u,T),_.fillStyle=o,_.globalAlpha=.9,_.fillRect(b+v-u,x,u,l((1-C/P)*T))}}},n})}(Ur)),Ur.exports}Xc();const Qc={key:0,args:[0,1,64]},Zc={key:1,args:[.5,1,64]},Jc={key:2},ef=["tone-mapped","map","side","color"];new ze(16777215);const jt=Fe({__name:"Range",props:{modelValue:null,min:{default:0},max:{default:100},step:{default:1},disabled:{type:Boolean,default:!1}},emits:["update:modelValue","mousedown"],setup(t,{emit:e}){const n=t,r=e,i=W(null);function o(b,x,v){return Math.min(Math.max(b,x),v)}function s(b){const x=b.toString();return x.includes("e-")?Number.parseInt(x.split("e-")[1],10):x.includes(".")?x.split(".")[1].length:0}function a(b,x){const v=s(x),T=10**(v+3);return Number.parseFloat((b*T/T).toFixed(v))}const l=Ue(()=>a(o(n.modelValue,n.min,n.max),n.step)),u=Ue(()=>{const b=(l.value-n.min)/(n.max-n.min)*100;return{width:`${b}%`,backgroundSize:`${b}% 100%`}});function c(b){if(!i.value)return l.value;const x=i.value.getBoundingClientRect(),T=(b.clientX-x.left)/x.width,I=n.max-n.min,_=n.min+I*T,C=Math.round(_/n.step)*n.step;return Math.min(Math.max(C,n.min),n.max)}function f(b){if(n.disabled)return;const x=c(b);r("update:modelValue",x)}function p(b){if(n.disabled)return;b.preventDefault();const x=c(b);r("update:modelValue",x),window.addEventListener("mousemove",f),window.addEventListener("mouseup",d)}function d(b){window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",d)}return Ft(()=>{window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",d)}),(b,x)=>(ee(),ie("span",{ref_key:"sliderRef",ref:i,class:at(["range-slider disabled:pointer-events-none disabled:cursor-default disabled:opacity-50",{disabled:t.disabled}]),bg:"[#e6e1fc] dark:[#676085]","touch-action-none":"",relative:"","inline-block":"","w-full":"","cursor-ew-resize":"","rounded-sm":"",onMousedown:p},[F("span",{style:Dr(u.value),bg:"[#cabeff] dark:[#4e34b9]",relative:"",block:"","rounded-sm":"",h:"[14px]"},null,4),F("span",{role:"slider",class:"slider-thumb",style:Dr({left:`${(l.value-t.min)/(t.max-t.min)*100}%`}),absolute:"","rounded-sm":"",w:"[1px]",h:"[14px]",bg:"zinc-100 dark:zinc-400",top:"50%",transform:"translate-x-[50%] translate-y-[-50%]"},null,4)],34))}});function uo(t,e){if(e===al)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),t;if(e===Or||e===ls){let n=t.getIndex();if(n===null){const s=[],a=t.getAttribute("position");if(a!==void 0){for(let l=0;l=2.0 are supported."));return}const u=new Df(o,{path:n||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c=0&&a[f]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+f+'".')}}u.setExtensions(s),u.setPlugins(a),u.parse(r,i)}parseAsync(e,n){const r=this;return new Promise(function(i,o){r.parse(e,n,i,o)})}}function nf(){let t={};return{get:function(e){return t[e]},add:function(e,n){t[e]=n},remove:function(e){delete t[e]},removeAll:function(){t={}}}}const he={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class rf{constructor(e){this.parser=e,this.name=he.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,n=this.parser.json.nodes||[];for(let r=0,i=n.length;r=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return n.loadTextureImage(e,o.source,s)}}class xf{constructor(e){this.parser=e,this.name=he.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const n=this.name,r=this.parser,i=r.json,o=i.textures[e];if(!o.extensions||!o.extensions[n])return null;const s=o.extensions[n],a=i.images[s.source];let l=r.textureLoader;if(a.uri){const u=r.options.manager.getHandler(a.uri);u!==null&&(l=u)}return this.detectSupport().then(function(u){if(u)return r.loadTextureImage(e,s.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(n)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const n=new Image;n.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",n.onload=n.onerror=function(){e(n.height===1)}})),this.isSupported}}class vf{constructor(e){this.parser=e,this.name=he.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const n=this.name,r=this.parser,i=r.json,o=i.textures[e];if(!o.extensions||!o.extensions[n])return null;const s=o.extensions[n],a=i.images[s.source];let l=r.textureLoader;if(a.uri){const u=r.options.manager.getHandler(a.uri);u!==null&&(l=u)}return this.detectSupport().then(function(u){if(u)return r.loadTextureImage(e,s.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(n)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const n=new Image;n.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",n.onload=n.onerror=function(){e(n.height===1)}})),this.isSupported}}class bf{constructor(e){this.name=he.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const n=this.parser.json,r=n.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const i=r.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(a){const l=i.byteOffset||0,u=i.byteLength||0,c=i.count,f=i.byteStride,p=new Uint8Array(a,l,u);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(c,f,p,i.mode,i.filter).then(function(d){return d.buffer}):s.ready.then(function(){const d=new ArrayBuffer(c*f);return s.decodeGltfBuffer(new Uint8Array(d),c,f,p,i.mode,i.filter),d})})}else return null}}class wf{constructor(e){this.name=he.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const n=this.parser.json,r=n.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;const i=n.meshes[r.mesh];for(const u of i.primitives)if(u.mode!==nt.TRIANGLES&&u.mode!==nt.TRIANGLE_STRIP&&u.mode!==nt.TRIANGLE_FAN&&u.mode!==void 0)return null;const s=r.extensions[this.name].attributes,a=[],l={};for(const u in s)a.push(this.parser.getDependency("accessor",s[u]).then(c=>(l[u]=c,l[u])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(u=>{const c=u.pop(),f=c.isGroup?c.children:[c],p=u[0].count,d=[];for(const b of f){const x=new xt,v=new se,T=new Fn,I=new se(1,1,1),_=new dl(b.geometry,b.material,p);for(let C=0;C0||t.search(/^data\:image\/jpeg/)===0?"image/jpeg":t.search(/\.webp($|\?)/i)>0||t.search(/^data\:image\/webp/)===0?"image/webp":t.search(/\.ktx2($|\?)/i)>0||t.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Pf=new xt;class Df{constructor(e={},n={}){this.json=e,this.extensions={},this.plugins={},this.options=n,this.cache=new nf,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let r=!1,i=-1,o=!1,s=-1;if(typeof navigator<"u"){const a=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(a)===!0;const l=a.match(/Version\/(\d+)/);i=r&&l?parseInt(l[1],10):-1,o=a.indexOf("Firefox")>-1,s=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||o&&s<98?this.textureLoader=new hl(this.options.manager):this.textureLoader=new ml(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new us(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,n){const r=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(s){const a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:r,userData:{}};return Rt(o,a,i),gt(a,i),Promise.all(r._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(const l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(n)}_markDefs(){const e=this.json.nodes||[],n=this.json.skins||[],r=this.json.meshes||[];for(let i=0,o=n.length;i{const l=this.associations.get(s);l!=null&&this.associations.set(a,l);for(const[u,c]of s.children.entries())o(c,a.children[u])};return o(r,i),i.name+="_instance_"+e.uses[n]++,i}_invokeOne(e){const n=Object.values(this.plugins);n.push(this);for(let r=0;r=2&&v.setY(g,h[M*l+1]),l>=3&&v.setZ(g,h[M*l+2]),l>=4&&v.setW(g,h[M*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}v.normalized=b}return v})}loadTexture(e){const n=this.json,r=this.options,o=n.textures[e].source,s=n.images[o];let a=this.textureLoader;if(s.uri){const l=r.manager.getHandler(s.uri);l!==null&&(a=l)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,n,r){const i=this,o=this.json,s=o.textures[e],a=o.images[n],l=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[l])return this.textureCache[l];const u=this.loadImageSource(n,r).then(function(c){c.flipY=!1,c.name=s.name||a.name||"",c.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(c.name=a.uri);const p=(o.samplers||{})[s.sampler]||{};return c.magFilter=fo[p.magFilter]||Bn,c.minFilter=fo[p.minFilter]||oi,c.wrapS=po[p.wrapS]||Un,c.wrapT=po[p.wrapT]||Un,c.generateMipmaps=!c.isCompressedTexture&&c.minFilter!==Lt&&c.minFilter!==Bn,i.associations.set(c,{textures:e}),c}).catch(function(){return null});return this.textureCache[l]=u,u}loadImageSource(e,n){const r=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(f=>f.clone());const s=i.images[e],a=self.URL||self.webkitURL;let l=s.uri||"",u=!1;if(s.bufferView!==void 0)l=r.getDependency("bufferView",s.bufferView).then(function(f){u=!0;const p=new Blob([f],{type:s.mimeType});return l=a.createObjectURL(p),l});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(l).then(function(f){return new Promise(function(p,d){let b=p;n.isImageBitmapLoader===!0&&(b=function(x){const v=new zn(x);v.needsUpdate=!0,p(v)}),n.load(cn.resolveURL(f,o.path),b,void 0,d)})}).then(function(f){return u===!0&&a.revokeObjectURL(l),gt(f,s),f.userData.mimeType=s.mimeType||Lf(s.uri),f}).catch(function(f){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),f});return this.sourceCache[e]=c,c}assignTexture(e,n,r,i){const o=this;return this.getDependency("texture",r.index).then(function(s){if(!s)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(s=s.clone(),s.channel=r.texCoord),o.extensions[he.KHR_TEXTURE_TRANSFORM]){const a=r.extensions!==void 0?r.extensions[he.KHR_TEXTURE_TRANSFORM]:void 0;if(a){const l=o.associations.get(s);s=o.extensions[he.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),o.associations.set(s,l)}}return i!==void 0&&(s.colorSpace=i),e[n]=s,s})}assignFinalMaterial(e){const n=e.geometry;let r=e.material;const i=n.attributes.tangent===void 0,o=n.attributes.color!==void 0,s=n.attributes.normal===void 0;if(e.isPoints){const a="PointsMaterial:"+r.uuid;let l=this.cache.get(a);l||(l=new gl,nr.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,l.sizeAttenuation=!1,this.cache.add(a,l)),r=l}else if(e.isLine){const a="LineBasicMaterial:"+r.uuid;let l=this.cache.get(a);l||(l=new yl,nr.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,this.cache.add(a,l)),r=l}if(i||o||s){let a="ClonedMaterial:"+r.uuid+":";i&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),s&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=r.clone(),o&&(l.vertexColors=!0),s&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(r))),r=l}e.material=r}getMaterialType(){return cs}loadMaterial(e){const n=this,r=this.json,i=this.extensions,o=r.materials[e];let s;const a={},l=o.extensions||{},u=[];if(l[he.KHR_MATERIALS_UNLIT]){const f=i[he.KHR_MATERIALS_UNLIT];s=f.getMaterialType(),u.push(f.extendParams(a,o,n))}else{const f=o.pbrMetallicRoughness||{};if(a.color=new ze(1,1,1),a.opacity=1,Array.isArray(f.baseColorFactor)){const p=f.baseColorFactor;a.color.setRGB(p[0],p[1],p[2],vt),a.opacity=p[3]}f.baseColorTexture!==void 0&&u.push(n.assignTexture(a,"map",f.baseColorTexture,mn)),a.metalness=f.metallicFactor!==void 0?f.metallicFactor:1,a.roughness=f.roughnessFactor!==void 0?f.roughnessFactor:1,f.metallicRoughnessTexture!==void 0&&(u.push(n.assignTexture(a,"metalnessMap",f.metallicRoughnessTexture)),u.push(n.assignTexture(a,"roughnessMap",f.metallicRoughnessTexture))),s=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=qn);const c=o.alphaMode||xr.OPAQUE;if(c===xr.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,c===xr.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&s!==Ht&&(u.push(n.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new Pe(1,1),o.normalTexture.scale!==void 0)){const f=o.normalTexture.scale;a.normalScale.set(f,f)}if(o.occlusionTexture!==void 0&&s!==Ht&&(u.push(n.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&s!==Ht){const f=o.emissiveFactor;a.emissive=new ze().setRGB(f[0],f[1],f[2],vt)}return o.emissiveTexture!==void 0&&s!==Ht&&u.push(n.assignTexture(a,"emissiveMap",o.emissiveTexture,mn)),Promise.all(u).then(function(){const f=new s(a);return o.name&&(f.name=o.name),gt(f,o),n.associations.set(f,{materials:e}),o.extensions&&Rt(i,f,o),f})}createUniqueName(e){const n=hn.sanitizeNodeName(e||"");return n in this.nodeNamesUsed?n+"_"+ ++this.nodeNamesUsed[n]:(this.nodeNamesUsed[n]=0,n)}loadGeometries(e){const n=this,r=this.extensions,i=this.primitiveCache;function o(a){return r[he.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,n).then(function(l){return ho(l,a,n)})}const s=[];for(let a=0,l=e.length;a0&&Cf(T,o),T.name=n.createUniqueName(o.name||"mesh_"+e),gt(T,o),v.extensions&&Rt(i,T,v),n.assignFinalMaterial(T),f.push(T)}for(let d=0,b=f.length;d1?c=new rr:u.length===1?c=u[0]:c=new si,c!==u[0])for(let f=0,p=u.length;f{const f=new Map;for(const[p,d]of i.associations)(p instanceof nr||p instanceof zn)&&f.set(p,d);return c.traverse(p=>{const d=i.associations.get(p);d!=null&&f.set(p,d)}),f};return i.associations=u(o),o})}_createAnimationTracks(e,n,r,i,o){const s=[],a=e.name?e.name:e.uuid,l=[];Tt[o.path]===Tt.weights?e.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(a);let u;switch(Tt[o.path]){case Tt.weights:u=Ni;break;case Tt.rotation:u=Li;break;case Tt.position:case Tt.scale:u=Ci;break;default:switch(r.itemSize){case 1:u=Ni;break;case 2:case 3:default:u=Ci;break}break}const c=i.interpolation!==void 0?Sf[i.interpolation]:ti,f=this._getArrayFromAccessor(r);for(let p=0,d=l.length;pnew _a(t)),Ct.register(t=>new Ea(t)),Ct)}async function Ff(t){const r=(await zs().loadAsync(t)).userData;if(!r.vrmAnimations){console.warn("No VRM animations found in the .vrma file");return}if(r.vrmAnimations.length===0){console.warn("No VRM animations found in the .vrma file");return}return r.vrmAnimations[0]}async function zf(t,e){if(!t){console.warn("No VRM found");return}if(e)return Ma(e,t)}function Bf(){const t=W(!1),e=W(0),n=W(0),r=.2,i=1,o=6,s=W(Math.random()*(o-i)+i);function a(l,u){if(l!=null&&l.expressionManager&&(n.value+=u,!t.value&&n.value>=s.value&&(t.value=!0,e.value=0),t.value)){e.value+=u/r;const c=Math.sin(Math.PI*e.value);l.expressionManager.setValue("blink",c),e.value>=1&&(t.value=!1,n.value=0,l.expressionManager.setValue("blink",0),s.value=Math.random()*(o-i)+i)}}return{update:a}}function Uf(){let t=-1,e,n=0;function r(){e?e.set(on(-.25,.25),on(-.2,.15),-.65):e=new se(on(-.25,.25),on(-.2,.15),-.65)}function i(o,s){var a;!(o!=null&&o.expressionManager)||!o.lookAt||(n>=t?(r(),n=0,t=Sa()/1e3):e||r(),o.lookAt.target||(o.lookAt.target=new si),o.lookAt.target.position.lerp(e,on(.2,.5)),(a=o.lookAt)==null||a.update(s),n+=s)}return{update:i}}async function jf(t,e){const i=(await zs().loadAsync(t,s=>{var a;return(a=e==null?void 0:e.onProgress)==null?void 0:a.call(e,s)})).userData;if(!i.vrm)return;const o=i.vrm;if(Nr.removeUnnecessaryVertices(o.scene),Nr.combineSkeletons(o.scene),o.scene.traverse(s=>{s.frustumCulled=!1}),o.lookAt){const s=new Ia(o.lookAt);s.name="lookAtQuaternionProxy",o.scene.add(s)}return e!=null&&e.scene&&e.scene.add(o.scene),e!=null&&e.position&&o.scene.position.set(...e.position),o}function Vf(t){const e=W(null),n=W(!1),r=W(0),i=W(new Map),o=W(new Map),s=W(),a=(T,I,_)=>T+(I-T)*_,l=T=>T<.5?4*T*T*T:1-(-2*T+2)**3/2,u=new Map([["happy",{expression:[{name:"happy",value:1,duration:.3},{name:"aa",value:.3}],blendDuration:.3}],["sad",{expression:[{name:"sad",value:1},{name:"oh",value:.2}],blendDuration:.3}],["angry",{expression:[{name:"angry",value:1},{name:"ee",value:.4}],blendDuration:.2}],["surprised",{expression:[{name:"Surprised",value:1},{name:"oh",value:.6}],blendDuration:.1}],["neutral",{expression:[{name:"neutral",value:1}],blendDuration:.5}]]),c=()=>{s.value&&(clearTimeout(s.value),s.value=void 0)},f=T=>{var _;if(c(),!u.has(T)){console.warn(`Emotion ${T} not found`);return}const I=u.get(T);if(e.value=T,n.value=!0,r.value=0,t.expressionManager){const C=Object.keys(t.expressionManager.expressionMap);for(const P of C)t.expressionManager.setValue(P,0)}i.value.clear(),o.value.clear();for(const C of I.expression||[]){const P=((_=t.expressionManager)==null?void 0:_.getValue(C.name))||0;i.value.set(C.name,P),o.value.set(C.name,C.value)}};return{currentEmotion:e,isTransitioning:n,setEmotion:f,setEmotionWithResetAfter:(T,I)=>{c(),f(T),s.value=setTimeout(()=>{f("neutral"),s.value=void 0},I)},update:T=>{var C;if(!n.value||!e.value)return;const _=u.get(e.value).blendDuration||.3;r.value+=T/_,r.value>=1&&(r.value=1,n.value=!1);for(const[P,h]of o.value){const M=i.value.get(P)||0,y=a(M,h,l(r.value));(C=t.expressionManager)==null||C.setValue(P,y)}},addEmotionState:(T,I)=>{u.set(T,I)},removeEmotionState:T=>{u.delete(T)},dispose:()=>{c()}}}const Hf=Fe({__name:"Model",props:{model:null,idleAnimation:null,loadAnimations:null,position:null,paused:{type:Boolean}},emits:["loadModelProgress","error"],setup(t,{expose:e,emit:n}){const r=t,i=n;let o;const s=W(),a=W(),{scene:l}=Yn(),{onBeforeRender:u}=On(),c=Bf(),f=Uf(),p=W();je(()=>r.position,([x,v,T])=>{s.value&&s.value.scene.position.set(x,v,T)}),pn(async()=>{if(l.value)try{const x=await jf(r.model,{scene:l.value,lookAt:!0,position:r.position,onProgress:I=>i("loadModelProgress",Number.parseFloat((100*(I.loaded/I.total)).toFixed(2)))});if(!x){console.warn("No VRM model loaded");return}const v=await Ff(r.idleAnimation),T=await zf(x,v);if(!T){console.warn("No VRM animation loaded");return}a.value=new Sl(x.scene),a.value.clipAction(T).play(),p.value=Vf(x),s.value=x,o=u(({delta:I})=>{var _,C,P;(_=a.value)==null||_.update(I),(C=s.value)==null||C.update(I),c.update(s.value,I),f.update(s.value,I),(P=p.value)==null||P.update(I)}).off}catch(x){i("error",x)}}),Ft(()=>{o==null||o(),s.value&&(s.value.scene.removeFromParent(),Nr.deepDispose(s.value.scene))}),e({setExpression(x){var v;(v=p.value)==null||v.setEmotionWithResetAfter(x,1e3)}});const{pause:d,resume:b}=On();return je(()=>r.paused,x=>{x?d():b()}),(x,v)=>gn(x.$slots,"default")}}),Gf=["position"],$f={absolute:"",bottom:"3",right:"3"},Yf={flex:"~ row","cursor-pointer":""},qf=["checked","aria-checked"],Kf={key:0,"min-w":"50vw",z:"{var x;(x=p.value)==null||x.setExpression(b)}}),(b,x)=>(ee(),Qt(ys,{relative:""},{default:Be(({height:v,width:T})=>[ke(H(Il),{alpha:!0,antialias:!0,width:T,height:v},{default:Be(()=>[ke(H(Rc)),F("TresPerspectiveCamera",{position:[s.value,a.value,l.value]},null,8,Gf),x[14]||(x[14]=F("TresDirectionalLight",{color:16777215,intensity:1.2,position:[1,1,1]},null,-1)),x[15]||(x[15]=F("TresAmbientLight",{color:16777215,intensity:1.5},null,-1)),ke(Hf,{ref_key:"modelRef",ref:p,model:r.model,"idle-animation":r.idleAnimation,position:[u.value,c.value,f.value],paused:r.paused,onLoadModelProgress:x[0]||(x[0]=I=>i("loadModelProgress",I)),onError:x[1]||(x[1]=I=>i("error",I))},null,8,["model","idle-animation","position","paused"])]),_:2},1032,["width","height"]),F("div",$f,[F("div",Yf,[F("label",{class:at([o.value?"bg-zinc-300 dark:bg-zinc-200":"bg-zinc-100 dark:bg-zinc-700"]),transition:"all ease-in-out duration-500",text:"lg zinc-500 dark:zinc-400","m-1":"","h-fit":"","w-fit":"","cursor-pointer":"","appearance-none":"","gap-1":"","rounded-lg":"","rounded-md":"","border-none":"","p-2":"","outline-none":""},[_t(F("input",{"onUpdate:modelValue":x[2]||(x[2]=I=>o.value=I),checked:o.value,"aria-checked":o.value,name:"showLive2DViewerInspector",type:"checkbox",hidden:"","appearance-none":"","outline-none":""},null,8,qf),[[Jr,o.value]]),x[16]||(x[16]=F("div",{"select-none":""},[F("div",{"i-solar:bug-bold-duotone":""})],-1))],2)]),ke(ci,null,{default:Be(()=>[o.value?(ee(),ie("div",Kf,[F("div",Wf,[F("div",Xf,[F("span",null,ge(H(d)("stage.viewers.debug-menu.vrm.model.title")),1)]),ke(Oi,{"h-fit":"","w-full":"",flex:"~ col",border:"~ gray/25 rounded-lg",divide:"y dashed gray/25","of-clip":"","shadow-sm":""},{label:Be(()=>[F("span",Qf,ge(H(d)("stage.viewers.debug-menu.vrm.camera")),1)]),default:Be(()=>[F("div",Zf,[x[17]||(x[17]=F("div",{text:"zinc-400 dark:zinc-500"},[F("span",null,"X")],-1)),F("label",Jf,[ke(jt,{modelValue:s.value,"onUpdate:modelValue":x[3]||(x[3]=I=>s.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),F("div",ed,[F("span",null,ge(s.value),1)]),x[18]||(x[18]=F("div",{text:"zinc-400 dark:zinc-500"},[F("span",null,"Y")],-1)),F("label",td,[ke(jt,{modelValue:a.value,"onUpdate:modelValue":x[4]||(x[4]=I=>a.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),F("div",nd,[F("span",null,ge(a.value),1)]),x[19]||(x[19]=F("div",{text:"zinc-400 dark:zinc-500"},[F("span",null,"Z")],-1)),F("label",rd,[ke(jt,{modelValue:l.value,"onUpdate:modelValue":x[5]||(x[5]=I=>l.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),F("div",id,[F("span",null,ge(l.value),1)])])]),_:1}),ke(Oi,{"h-fit":"","w-full":"",flex:"~ col",border:"~ gray/25 rounded-lg",divide:"y dashed gray/25","of-clip":"","shadow-sm":""},{label:Be(()=>[F("span",od,ge(H(d)("stage.viewers.debug-menu.vrm.model.title")),1)]),default:Be(()=>[F("div",sd,[x[20]||(x[20]=F("div",{text:"zinc-400 dark:zinc-500"},[F("span",null,"X")],-1)),F("label",ad,[ke(jt,{modelValue:u.value,"onUpdate:modelValue":x[6]||(x[6]=I=>u.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),F("div",ld,[F("span",null,ge(u.value),1)]),x[21]||(x[21]=F("div",{text:"zinc-400 dark:zinc-500"},[F("span",null,"Y")],-1)),F("label",ud,[ke(jt,{modelValue:c.value,"onUpdate:modelValue":x[7]||(x[7]=I=>c.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),F("div",cd,[F("span",null,ge(c.value),1)]),x[22]||(x[22]=F("div",{text:"zinc-400 dark:zinc-500"},[F("span",null,"Z")],-1)),F("label",fd,[ke(jt,{modelValue:f.value,"onUpdate:modelValue":x[8]||(x[8]=I=>f.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),F("div",dd,[F("span",null,ge(f.value),1)])])]),_:1}),F("div",pd,[F("span",null,ge(H(d)("stage.viewers.debug-menu.emotions")),1)]),F("div",hd,[F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[9]||(x[9]=I=>{var _;return(_=p.value)==null?void 0:_.setExpression("neutral")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.neutral")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[10]||(x[10]=I=>{var _;return(_=p.value)==null?void 0:_.setExpression("surprised")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.surprised")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[11]||(x[11]=I=>{var _;return(_=p.value)==null?void 0:_.setExpression("sad")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.sad")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[12]||(x[12]=I=>{var _;return(_=p.value)==null?void 0:_.setExpression("angry")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.angry")),1),F("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[13]||(x[13]=I=>{var _;return(_=p.value)==null?void 0:_.setExpression("happy")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.happy")),1)])])])):it("",!0)]),_:1})])]),_:1}))}}),gd=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];class bn{constructor(e,n,r){this.normal=n,this.property=e,r&&(this.space=r)}}bn.prototype.normal={};bn.prototype.property={};bn.prototype.space=void 0;function Bs(t,e){const n={},r={};for(const i of t)Object.assign(n,i.property),Object.assign(r,i.normal);return new bn(n,r,e)}function Hr(t){return t.toLowerCase()}class Ke{constructor(e,n){this.attribute=n,this.property=e}}Ke.prototype.attribute="";Ke.prototype.booleanish=!1;Ke.prototype.boolean=!1;Ke.prototype.commaOrSpaceSeparated=!1;Ke.prototype.commaSeparated=!1;Ke.prototype.defined=!1;Ke.prototype.mustUseProperty=!1;Ke.prototype.number=!1;Ke.prototype.overloadedBoolean=!1;Ke.prototype.property="";Ke.prototype.spaceSeparated=!1;Ke.prototype.space=void 0;let yd=0;const fe=zt(),Le=zt(),Us=zt(),$=zt(),Re=zt(),Kt=zt(),Qe=zt();function zt(){return 2**++yd}const Gr=Object.freeze(Object.defineProperty({__proto__:null,boolean:fe,booleanish:Le,commaOrSpaceSeparated:Qe,commaSeparated:Kt,number:$,overloadedBoolean:Us,spaceSeparated:Re},Symbol.toStringTag,{value:"Module"})),br=Object.keys(Gr);class hi extends Ke{constructor(e,n,r,i){let o=-1;if(super(e,n),mo(this,"space",i),typeof r=="number")for(;++o4&&n.slice(0,4)==="data"&&wd.test(e)){if(e.charAt(4)==="-"){const o=e.slice(5).replace(go,Ad);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=e.slice(4);if(!go.test(o)){let s=o.replace(bd,kd);s.charAt(0)!=="-"&&(s="-"+s),e="data"+s}}i=hi}return new i(r,e)}function kd(t){return"-"+t.toLowerCase()}function Ad(t){return t.charAt(1).toUpperCase()}const _d=Bs([js,xd,Gs,$s,Ys],"html"),qs=Bs([js,vd,Gs,$s,Ys],"svg"),yo={}.hasOwnProperty;function Ed(t,e){const n=e||{};function r(i,...o){let s=r.invalid;const a=r.handlers;if(i&&yo.call(i,t)){const l=String(i[t]);s=yo.call(a,l)?a[l]:r.unknown}if(s)return s.call(this,i,...o)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}const Md=/^>|^->||--!>|"],Id=["<",">"];function Rd(t,e,n,r){return r.settings.bogusComments?"":"";function i(o){return Yt(o,Object.assign({},r.settings.characterReferences,{subset:Id}))}}function Cd(t,e,n,r){return""}function Nd(t,e){const n=e||{};return(t[t.length-1]===""?[...t,""]:t).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}function Ld(t){return t.join(" ").trim()}const Pd=/[ \t\n\f\r]/g;function mi(t){return typeof t=="object"?t.type==="text"?xo(t.value):!1:xo(t)}function xo(t){return t.replace(Pd,"")===""}const De=Ws(1),Ks=Ws(-1),Dd=[];function Ws(t){return e;function e(n,r,i){const o=n?n.children:Dd;let s=(r||0)+t,a=o[s];if(!i)for(;a&&mi(a);)s+=t,a=o[s];return a}}const Od={}.hasOwnProperty;function Xs(t){return e;function e(n,r,i){return Od.call(t,n.tagName)&&t[n.tagName](n,r,i)}}const gi=Xs({body:zd,caption:wr,colgroup:wr,dd:Vd,dt:jd,head:wr,html:Fd,li:Ud,optgroup:Hd,option:Gd,p:Bd,rp:vo,rt:vo,tbody:Yd,td:bo,tfoot:qd,th:bo,thead:$d,tr:Kd});function wr(t,e,n){const r=De(n,e,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&mi(r.value.charAt(0)))}function Fd(t,e,n){const r=De(n,e);return!r||r.type!=="comment"}function zd(t,e,n){const r=De(n,e);return!r||r.type!=="comment"}function Bd(t,e,n){const r=De(n,e);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!n||!(n.type==="element"&&(n.tagName==="a"||n.tagName==="audio"||n.tagName==="del"||n.tagName==="ins"||n.tagName==="map"||n.tagName==="noscript"||n.tagName==="video"))}function Ud(t,e,n){const r=De(n,e);return!r||r.type==="element"&&r.tagName==="li"}function jd(t,e,n){const r=De(n,e);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function Vd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function vo(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function Hd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&r.tagName==="optgroup"}function Gd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function $d(t,e,n){const r=De(n,e);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function Yd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function qd(t,e,n){return!De(n,e)}function Kd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&r.tagName==="tr"}function bo(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}const Wd=Xs({body:Zd,colgroup:Jd,head:Qd,html:Xd,tbody:ep});function Xd(t){const e=De(t,-1);return!e||e.type!=="comment"}function Qd(t){const e=new Set;for(const r of t.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(e.has(r.tagName))return!1;e.add(r.tagName)}const n=t.children[0];return!n||n.type==="element"}function Zd(t){const e=De(t,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&mi(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function Jd(t,e,n){const r=Ks(n,e),i=De(t,-1,!0);return n&&r&&r.type==="element"&&r.tagName==="colgroup"&&gi(r,n.children.indexOf(r),n)?!1:!!(i&&i.type==="element"&&i.tagName==="col")}function ep(t,e,n){const r=Ks(n,e),i=De(t,-1);return n&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&gi(r,n.children.indexOf(r),n)?!1:!!(i&&i.type==="element"&&i.tagName==="tr")}const In={name:[[` +}`;const vn=new ae(0,0,0),pi=new ae(0,0,0),jc=new ae(0,0,0);function so(t,e,n){const r=vn.setFromMatrixPosition(t.matrixWorld);r.project(e);const i=n.width/2,o=n.height/2;return[(Number.isNaN(r.x)?0:r.x)*i+i,-(r.y*o)+o,r.z]}function Vc(t,e){const n=vn.setFromMatrixPosition(t.matrixWorld),r=pi.setFromMatrixPosition(e.matrixWorld),i=n.sub(r),o=e.getWorldDirection(jc);return i.angleTo(o)>Math.PI/2}function Hc(t,e,n,r){const i=vn.setFromMatrixPosition(t.matrixWorld),o=i.clone();o.project(e),n.setFromCamera(new Pe(o.x,o.y),e);const a=n.intersectObjects(r,!0);if(a.length>0){const s=a[0].distance;return i.distanceTo(n.ray.origin)Math.abs(t)<1e-10?0:t;function Da(t,e,n=""){let r="matrix3d(";for(let i=0;i!==16;i++)r+=Br(e[i]*t.elements[i])+(i!==15?",":")");return n+r}const qc=(t=>e=>Da(e,t))([1,-1,1,1,1,-1,1,1,1,-1,1,1,1,-1,1,1]),Yc=(t=>(e,n)=>Da(e,t(n),"translate(-50%,-50%)"))(t=>[1/t,1/t,1/t,1,-1/t,-1/t,-1/t,-1,1/t,1/t,1/t,1,1,1,1,1]),Kc=["geometry","material"];new ta;var Ur={exports:{}},Wc=Ur.exports,lo;function Xc(){return lo||(lo=1,function(t,e){(function(n,r){t.exports=r()})(Wc,function(){var n=function(){function r(d){return a.appendChild(d.dom),d}function i(d){for(var b=0;bl+1e3&&(c.update(1e3*u/(d-l),100),l=d,u=0,p)){var b=performance.memory;p.update(b.usedJSHeapSize/1048576,b.jsHeapSizeLimit/1048576)}return d},update:function(){s=this.end()},domElement:a,setMode:i}};return n.Panel=function(r,i,o){var a=1/0,s=0,l=Math.round,u=l(window.devicePixelRatio||1),c=80*u,f=48*u,p=3*u,d=2*u,b=3*u,x=15*u,v=74*u,T=30*u,I=document.createElement("canvas");I.width=c,I.height=f,I.style.cssText="width:80px;height:48px";var A=I.getContext("2d");return A.font="bold "+9*u+"px Helvetica,Arial,sans-serif",A.textBaseline="top",A.fillStyle=o,A.fillRect(0,0,c,f),A.fillStyle=i,A.fillText(r,p,d),A.fillRect(b,x,v,T),A.fillStyle=o,A.globalAlpha=.9,A.fillRect(b,x,v,T),{dom:I,update:function(C,P){a=Math.min(a,C),s=Math.max(s,C),A.fillStyle=o,A.globalAlpha=1,A.fillRect(0,0,c,x),A.fillStyle=i,A.fillText(l(C)+" "+r+" ("+l(a)+"-"+l(s)+")",p,d),A.drawImage(I,b+u,x,v-u,T,b,x,v-u,T),A.fillRect(b+v-u,x,u,T),A.fillStyle=o,A.globalAlpha=.9,A.fillRect(b+v-u,x,u,l((1-C/P)*T))}}},n})}(Ur)),Ur.exports}Xc();const Qc={key:0,args:[0,1,64]},Zc={key:1,args:[.5,1,64]},Jc={key:2},ef=["tone-mapped","map","side","color"];new Fe(16777215);const jt=ze({__name:"Range",props:{modelValue:null,min:{default:0},max:{default:100},step:{default:1},disabled:{type:Boolean,default:!1}},emits:["update:modelValue","mousedown"],setup(t,{emit:e}){const n=t,r=e,i=W(null);function o(b,x,v){return Math.min(Math.max(b,x),v)}function a(b){const x=b.toString();return x.includes("e-")?Number.parseInt(x.split("e-")[1],10):x.includes(".")?x.split(".")[1].length:0}function s(b,x){const v=a(x),T=10**(v+3);return Number.parseFloat((b*T/T).toFixed(v))}const l=Ue(()=>s(o(n.modelValue,n.min,n.max),n.step)),u=Ue(()=>{const b=(l.value-n.min)/(n.max-n.min)*100;return{width:`${b}%`,backgroundSize:`${b}% 100%`}});function c(b){if(!i.value)return l.value;const x=i.value.getBoundingClientRect(),T=(b.clientX-x.left)/x.width,I=n.max-n.min,A=n.min+I*T,C=Math.round(A/n.step)*n.step;return Math.min(Math.max(C,n.min),n.max)}function f(b){if(n.disabled)return;const x=c(b);r("update:modelValue",x)}function p(b){if(n.disabled)return;b.preventDefault();const x=c(b);r("update:modelValue",x),window.addEventListener("mousemove",f),window.addEventListener("mouseup",d)}function d(b){window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",d)}return zt(()=>{window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",d)}),(b,x)=>(ee(),ie("span",{ref_key:"sliderRef",ref:i,class:st(["range-slider disabled:pointer-events-none disabled:cursor-default disabled:opacity-50",{disabled:t.disabled}]),bg:"[#e6e1fc] dark:[#676085]","touch-action-none":"",relative:"","inline-block":"","w-full":"","cursor-ew-resize":"","rounded-sm":"",onMousedown:p},[z("span",{style:Dr(u.value),bg:"[#cabeff] dark:[#4e34b9]",relative:"",block:"","rounded-sm":"",h:"[14px]"},null,4),z("span",{role:"slider",class:"slider-thumb",style:Dr({left:`${(l.value-t.min)/(t.max-t.min)*100}%`}),absolute:"","rounded-sm":"",w:"[1px]",h:"[14px]",bg:"zinc-100 dark:zinc-400",top:"50%",transform:"translate-x-[50%] translate-y-[-50%]"},null,4)],34))}});function uo(t,e){if(e===sl)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),t;if(e===Or||e===la){let n=t.getIndex();if(n===null){const a=[],s=t.getAttribute("position");if(s!==void 0){for(let l=0;l=2.0 are supported."));return}const u=new Df(o,{path:n||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});u.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c=0&&s[f]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+f+'".')}}u.setExtensions(a),u.setPlugins(s),u.parse(r,i)}parseAsync(e,n){const r=this;return new Promise(function(i,o){r.parse(e,n,i,o)})}}function nf(){let t={};return{get:function(e){return t[e]},add:function(e,n){t[e]=n},remove:function(e){delete t[e]},removeAll:function(){t={}}}}const he={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class rf{constructor(e){this.parser=e,this.name=he.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,n=this.parser.json.nodes||[];for(let r=0,i=n.length;r=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return n.loadTextureImage(e,o.source,a)}}class xf{constructor(e){this.parser=e,this.name=he.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){const n=this.name,r=this.parser,i=r.json,o=i.textures[e];if(!o.extensions||!o.extensions[n])return null;const a=o.extensions[n],s=i.images[a.source];let l=r.textureLoader;if(s.uri){const u=r.options.manager.getHandler(s.uri);u!==null&&(l=u)}return this.detectSupport().then(function(u){if(u)return r.loadTextureImage(e,a.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(n)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const n=new Image;n.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",n.onload=n.onerror=function(){e(n.height===1)}})),this.isSupported}}class vf{constructor(e){this.parser=e,this.name=he.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){const n=this.name,r=this.parser,i=r.json,o=i.textures[e];if(!o.extensions||!o.extensions[n])return null;const a=o.extensions[n],s=i.images[a.source];let l=r.textureLoader;if(s.uri){const u=r.options.manager.getHandler(s.uri);u!==null&&(l=u)}return this.detectSupport().then(function(u){if(u)return r.loadTextureImage(e,a.source,l);if(i.extensionsRequired&&i.extensionsRequired.indexOf(n)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){const n=new Image;n.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",n.onload=n.onerror=function(){e(n.height===1)}})),this.isSupported}}class bf{constructor(e){this.name=he.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const n=this.parser.json,r=n.bufferViews[e];if(r.extensions&&r.extensions[this.name]){const i=r.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),a=this.parser.options.meshoptDecoder;if(!a||!a.supported){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(s){const l=i.byteOffset||0,u=i.byteLength||0,c=i.count,f=i.byteStride,p=new Uint8Array(s,l,u);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(c,f,p,i.mode,i.filter).then(function(d){return d.buffer}):a.ready.then(function(){const d=new ArrayBuffer(c*f);return a.decodeGltfBuffer(new Uint8Array(d),c,f,p,i.mode,i.filter),d})})}else return null}}class wf{constructor(e){this.name=he.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const n=this.parser.json,r=n.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;const i=n.meshes[r.mesh];for(const u of i.primitives)if(u.mode!==nt.TRIANGLES&&u.mode!==nt.TRIANGLE_STRIP&&u.mode!==nt.TRIANGLE_FAN&&u.mode!==void 0)return null;const a=r.extensions[this.name].attributes,s=[],l={};for(const u in a)s.push(this.parser.getDependency("accessor",a[u]).then(c=>(l[u]=c,l[u])));return s.length<1?null:(s.push(this.parser.createNodeMesh(e)),Promise.all(s).then(u=>{const c=u.pop(),f=c.isGroup?c.children:[c],p=u[0].count,d=[];for(const b of f){const x=new xt,v=new ae,T=new zn,I=new ae(1,1,1),A=new dl(b.geometry,b.material,p);for(let C=0;C0||t.search(/^data\:image\/jpeg/)===0?"image/jpeg":t.search(/\.webp($|\?)/i)>0||t.search(/^data\:image\/webp/)===0?"image/webp":t.search(/\.ktx2($|\?)/i)>0||t.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const Pf=new xt;class Df{constructor(e={},n={}){this.json=e,this.extensions={},this.plugins={},this.options=n,this.cache=new nf,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let r=!1,i=-1,o=!1,a=-1;if(typeof navigator<"u"){const s=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(s)===!0;const l=s.match(/Version\/(\d+)/);i=r&&l?parseInt(l[1],10):-1,o=s.indexOf("Firefox")>-1,a=o?s.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||o&&a<98?this.textureLoader=new hl(this.options.manager):this.textureLoader=new ml(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ua(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,n){const r=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(a){const s={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:r,userData:{}};return Rt(o,s,i),gt(s,i),Promise.all(r._invokeAll(function(l){return l.afterRoot&&l.afterRoot(s)})).then(function(){for(const l of s.scenes)l.updateMatrixWorld();e(s)})}).catch(n)}_markDefs(){const e=this.json.nodes||[],n=this.json.skins||[],r=this.json.meshes||[];for(let i=0,o=n.length;i{const l=this.associations.get(a);l!=null&&this.associations.set(s,l);for(const[u,c]of a.children.entries())o(c,s.children[u])};return o(r,i),i.name+="_instance_"+e.uses[n]++,i}_invokeOne(e){const n=Object.values(this.plugins);n.push(this);for(let r=0;r=2&&v.setY(g,h[S*l+1]),l>=3&&v.setZ(g,h[S*l+2]),l>=4&&v.setW(g,h[S*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}v.normalized=b}return v})}loadTexture(e){const n=this.json,r=this.options,o=n.textures[e].source,a=n.images[o];let s=this.textureLoader;if(a.uri){const l=r.manager.getHandler(a.uri);l!==null&&(s=l)}return this.loadTextureImage(e,o,s)}loadTextureImage(e,n,r){const i=this,o=this.json,a=o.textures[e],s=o.images[n],l=(s.uri||s.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];const u=this.loadImageSource(n,r).then(function(c){c.flipY=!1,c.name=a.name||s.name||"",c.name===""&&typeof s.uri=="string"&&s.uri.startsWith("data:image/")===!1&&(c.name=s.uri);const p=(o.samplers||{})[a.sampler]||{};return c.magFilter=fo[p.magFilter]||Bn,c.minFilter=fo[p.minFilter]||oi,c.wrapS=po[p.wrapS]||Un,c.wrapT=po[p.wrapT]||Un,c.generateMipmaps=!c.isCompressedTexture&&c.minFilter!==Lt&&c.minFilter!==Bn,i.associations.set(c,{textures:e}),c}).catch(function(){return null});return this.textureCache[l]=u,u}loadImageSource(e,n){const r=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(f=>f.clone());const a=i.images[e],s=self.URL||self.webkitURL;let l=a.uri||"",u=!1;if(a.bufferView!==void 0)l=r.getDependency("bufferView",a.bufferView).then(function(f){u=!0;const p=new Blob([f],{type:a.mimeType});return l=s.createObjectURL(p),l});else if(a.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const c=Promise.resolve(l).then(function(f){return new Promise(function(p,d){let b=p;n.isImageBitmapLoader===!0&&(b=function(x){const v=new Fn(x);v.needsUpdate=!0,p(v)}),n.load(cn.resolveURL(f,o.path),b,void 0,d)})}).then(function(f){return u===!0&&s.revokeObjectURL(l),gt(f,a),f.userData.mimeType=a.mimeType||Lf(a.uri),f}).catch(function(f){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),f});return this.sourceCache[e]=c,c}assignTexture(e,n,r,i){const o=this;return this.getDependency("texture",r.index).then(function(a){if(!a)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(a=a.clone(),a.channel=r.texCoord),o.extensions[he.KHR_TEXTURE_TRANSFORM]){const s=r.extensions!==void 0?r.extensions[he.KHR_TEXTURE_TRANSFORM]:void 0;if(s){const l=o.associations.get(a);a=o.extensions[he.KHR_TEXTURE_TRANSFORM].extendTexture(a,s),o.associations.set(a,l)}}return i!==void 0&&(a.colorSpace=i),e[n]=a,a})}assignFinalMaterial(e){const n=e.geometry;let r=e.material;const i=n.attributes.tangent===void 0,o=n.attributes.color!==void 0,a=n.attributes.normal===void 0;if(e.isPoints){const s="PointsMaterial:"+r.uuid;let l=this.cache.get(s);l||(l=new gl,nr.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,l.sizeAttenuation=!1,this.cache.add(s,l)),r=l}else if(e.isLine){const s="LineBasicMaterial:"+r.uuid;let l=this.cache.get(s);l||(l=new yl,nr.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,this.cache.add(s,l)),r=l}if(i||o||a){let s="ClonedMaterial:"+r.uuid+":";i&&(s+="derivative-tangents:"),o&&(s+="vertex-colors:"),a&&(s+="flat-shading:");let l=this.cache.get(s);l||(l=r.clone(),o&&(l.vertexColors=!0),a&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(s,l),this.associations.set(l,this.associations.get(r))),r=l}e.material=r}getMaterialType(){return ca}loadMaterial(e){const n=this,r=this.json,i=this.extensions,o=r.materials[e];let a;const s={},l=o.extensions||{},u=[];if(l[he.KHR_MATERIALS_UNLIT]){const f=i[he.KHR_MATERIALS_UNLIT];a=f.getMaterialType(),u.push(f.extendParams(s,o,n))}else{const f=o.pbrMetallicRoughness||{};if(s.color=new Fe(1,1,1),s.opacity=1,Array.isArray(f.baseColorFactor)){const p=f.baseColorFactor;s.color.setRGB(p[0],p[1],p[2],vt),s.opacity=p[3]}f.baseColorTexture!==void 0&&u.push(n.assignTexture(s,"map",f.baseColorTexture,mn)),s.metalness=f.metallicFactor!==void 0?f.metallicFactor:1,s.roughness=f.roughnessFactor!==void 0?f.roughnessFactor:1,f.metallicRoughnessTexture!==void 0&&(u.push(n.assignTexture(s,"metalnessMap",f.metallicRoughnessTexture)),u.push(n.assignTexture(s,"roughnessMap",f.metallicRoughnessTexture))),a=this._invokeOne(function(p){return p.getMaterialType&&p.getMaterialType(e)}),u.push(Promise.all(this._invokeAll(function(p){return p.extendMaterialParams&&p.extendMaterialParams(e,s)})))}o.doubleSided===!0&&(s.side=Yn);const c=o.alphaMode||xr.OPAQUE;if(c===xr.BLEND?(s.transparent=!0,s.depthWrite=!1):(s.transparent=!1,c===xr.MASK&&(s.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&a!==Ht&&(u.push(n.assignTexture(s,"normalMap",o.normalTexture)),s.normalScale=new Pe(1,1),o.normalTexture.scale!==void 0)){const f=o.normalTexture.scale;s.normalScale.set(f,f)}if(o.occlusionTexture!==void 0&&a!==Ht&&(u.push(n.assignTexture(s,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&a!==Ht){const f=o.emissiveFactor;s.emissive=new Fe().setRGB(f[0],f[1],f[2],vt)}return o.emissiveTexture!==void 0&&a!==Ht&&u.push(n.assignTexture(s,"emissiveMap",o.emissiveTexture,mn)),Promise.all(u).then(function(){const f=new a(s);return o.name&&(f.name=o.name),gt(f,o),n.associations.set(f,{materials:e}),o.extensions&&Rt(i,f,o),f})}createUniqueName(e){const n=hn.sanitizeNodeName(e||"");return n in this.nodeNamesUsed?n+"_"+ ++this.nodeNamesUsed[n]:(this.nodeNamesUsed[n]=0,n)}loadGeometries(e){const n=this,r=this.extensions,i=this.primitiveCache;function o(s){return r[he.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(s,n).then(function(l){return ho(l,s,n)})}const a=[];for(let s=0,l=e.length;s0&&Cf(T,o),T.name=n.createUniqueName(o.name||"mesh_"+e),gt(T,o),v.extensions&&Rt(i,T,v),n.assignFinalMaterial(T),f.push(T)}for(let d=0,b=f.length;d1?c=new rr:u.length===1?c=u[0]:c=new ai,c!==u[0])for(let f=0,p=u.length;f{const f=new Map;for(const[p,d]of i.associations)(p instanceof nr||p instanceof Fn)&&f.set(p,d);return c.traverse(p=>{const d=i.associations.get(p);d!=null&&f.set(p,d)}),f};return i.associations=u(o),o})}_createAnimationTracks(e,n,r,i,o){const a=[],s=e.name?e.name:e.uuid,l=[];Tt[o.path]===Tt.weights?e.traverse(function(p){p.morphTargetInfluences&&l.push(p.name?p.name:p.uuid)}):l.push(s);let u;switch(Tt[o.path]){case Tt.weights:u=Ni;break;case Tt.rotation:u=Li;break;case Tt.position:case Tt.scale:u=Ci;break;default:switch(r.itemSize){case 1:u=Ni;break;case 2:case 3:default:u=Ci;break}break}const c=i.interpolation!==void 0?Sf[i.interpolation]:ti,f=this._getArrayFromAccessor(r);for(let p=0,d=l.length;pnew As(t)),Ct.register(t=>new Es(t)),Ct)}async function zf(t){const r=(await Fa().loadAsync(t)).userData;if(!r.vrmAnimations){console.warn("No VRM animations found in the .vrma file");return}if(r.vrmAnimations.length===0){console.warn("No VRM animations found in the .vrma file");return}return r.vrmAnimations[0]}async function Ff(t,e){if(!t){console.warn("No VRM found");return}if(e)return Ms(e,t)}function Bf(){const t=W(!1),e=W(0),n=W(0),r=.2,i=1,o=6,a=W(Math.random()*(o-i)+i);function s(l,u){if(l!=null&&l.expressionManager&&(n.value+=u,!t.value&&n.value>=a.value&&(t.value=!0,e.value=0),t.value)){e.value+=u/r;const c=Math.sin(Math.PI*e.value);l.expressionManager.setValue("blink",c),e.value>=1&&(t.value=!1,n.value=0,l.expressionManager.setValue("blink",0),a.value=Math.random()*(o-i)+i)}}return{update:s}}function Uf(){let t=-1,e,n=0;function r(){e?e.set(on(-.25,.25),on(-.2,.15),-.65):e=new ae(on(-.25,.25),on(-.2,.15),-.65)}function i(o,a){var s;!(o!=null&&o.expressionManager)||!o.lookAt||(n>=t?(r(),n=0,t=Ss()/1e3):e||r(),o.lookAt.target||(o.lookAt.target=new ai),o.lookAt.target.position.lerp(e,on(.2,.5)),(s=o.lookAt)==null||s.update(a),n+=a)}return{update:i}}async function jf(t,e){const i=(await Fa().loadAsync(t,a=>{var s;return(s=e==null?void 0:e.onProgress)==null?void 0:s.call(e,a)})).userData;if(!i.vrm)return;const o=i.vrm;if(Nr.removeUnnecessaryVertices(o.scene),Nr.combineSkeletons(o.scene),o.scene.traverse(a=>{a.frustumCulled=!1}),o.lookAt){const a=new Is(o.lookAt);a.name="lookAtQuaternionProxy",o.scene.add(a)}return e!=null&&e.scene&&e.scene.add(o.scene),e!=null&&e.position&&o.scene.position.set(...e.position),o}function Vf(t){const e=W(null),n=W(!1),r=W(0),i=W(new Map),o=W(new Map),a=W(),s=(T,I,A)=>T+(I-T)*A,l=T=>T<.5?4*T*T*T:1-(-2*T+2)**3/2,u=new Map([["happy",{expression:[{name:"happy",value:1,duration:.3},{name:"aa",value:.3}],blendDuration:.3}],["sad",{expression:[{name:"sad",value:1},{name:"oh",value:.2}],blendDuration:.3}],["angry",{expression:[{name:"angry",value:1},{name:"ee",value:.4}],blendDuration:.2}],["surprised",{expression:[{name:"Surprised",value:1},{name:"oh",value:.6}],blendDuration:.1}],["neutral",{expression:[{name:"neutral",value:1}],blendDuration:.5}]]),c=()=>{a.value&&(clearTimeout(a.value),a.value=void 0)},f=T=>{var A;if(c(),!u.has(T)){console.warn(`Emotion ${T} not found`);return}const I=u.get(T);if(e.value=T,n.value=!0,r.value=0,t.expressionManager){const C=Object.keys(t.expressionManager.expressionMap);for(const P of C)t.expressionManager.setValue(P,0)}i.value.clear(),o.value.clear();for(const C of I.expression||[]){const P=((A=t.expressionManager)==null?void 0:A.getValue(C.name))||0;i.value.set(C.name,P),o.value.set(C.name,C.value)}};return{currentEmotion:e,isTransitioning:n,setEmotion:f,setEmotionWithResetAfter:(T,I)=>{c(),f(T),a.value=setTimeout(()=>{f("neutral"),a.value=void 0},I)},update:T=>{var C;if(!n.value||!e.value)return;const A=u.get(e.value).blendDuration||.3;r.value+=T/A,r.value>=1&&(r.value=1,n.value=!1);for(const[P,h]of o.value){const S=i.value.get(P)||0,y=s(S,h,l(r.value));(C=t.expressionManager)==null||C.setValue(P,y)}},addEmotionState:(T,I)=>{u.set(T,I)},removeEmotionState:T=>{u.delete(T)},dispose:()=>{c()}}}const Hf=ze({__name:"Model",props:{model:null,idleAnimation:null,loadAnimations:null,position:null,paused:{type:Boolean}},emits:["loadModelProgress","error"],setup(t,{expose:e,emit:n}){const r=t,i=n;let o;const a=W(),s=W(),{scene:l}=qn(),{onBeforeRender:u}=On(),c=Bf(),f=Uf(),p=W();je(()=>r.position,([x,v,T])=>{a.value&&a.value.scene.position.set(x,v,T)}),pn(async()=>{if(l.value)try{const x=await jf(r.model,{scene:l.value,lookAt:!0,position:r.position,onProgress:I=>i("loadModelProgress",Number.parseFloat((100*(I.loaded/I.total)).toFixed(2)))});if(!x){console.warn("No VRM model loaded");return}const v=await zf(r.idleAnimation),T=await Ff(x,v);if(!T){console.warn("No VRM animation loaded");return}s.value=new Sl(x.scene),s.value.clipAction(T).play(),p.value=Vf(x),a.value=x,o=u(({delta:I})=>{var A,C,P;(A=s.value)==null||A.update(I),(C=a.value)==null||C.update(I),c.update(a.value,I),f.update(a.value,I),(P=p.value)==null||P.update(I)}).off}catch(x){i("error",x)}}),zt(()=>{o==null||o(),a.value&&(a.value.scene.removeFromParent(),Nr.deepDispose(a.value.scene))}),e({setExpression(x){var v;(v=p.value)==null||v.setEmotionWithResetAfter(x,1e3)}});const{pause:d,resume:b}=On();return je(()=>r.paused,x=>{x?d():b()}),(x,v)=>gn(x.$slots,"default")}}),Gf=["position"],$f={absolute:"",bottom:"3",right:"3"},qf={flex:"~ row","cursor-pointer":""},Yf=["checked","aria-checked"],Kf={key:0,"min-w":"50vw",z:"{var x;(x=p.value)==null||x.setExpression(b)}}),(b,x)=>(ee(),Qt(ya,{relative:""},{default:Be(({height:v,width:T})=>[ke(H(Il),{alpha:!0,antialias:!0,width:T,height:v},{default:Be(()=>[ke(H(Rc)),z("TresPerspectiveCamera",{position:[a.value,s.value,l.value]},null,8,Gf),x[14]||(x[14]=z("TresDirectionalLight",{color:16777215,intensity:1.2,position:[1,1,1]},null,-1)),x[15]||(x[15]=z("TresAmbientLight",{color:16777215,intensity:1.5},null,-1)),ke(Hf,{ref_key:"modelRef",ref:p,model:r.model,"idle-animation":r.idleAnimation,position:[u.value,c.value,f.value],paused:r.paused,onLoadModelProgress:x[0]||(x[0]=I=>i("loadModelProgress",I)),onError:x[1]||(x[1]=I=>i("error",I))},null,8,["model","idle-animation","position","paused"])]),_:2},1032,["width","height"]),z("div",$f,[z("div",qf,[z("label",{class:st([o.value?"bg-zinc-300 dark:bg-zinc-200":"bg-zinc-100 dark:bg-zinc-700"]),transition:"all ease-in-out duration-500",text:"lg zinc-500 dark:zinc-400","m-1":"","h-fit":"","w-fit":"","cursor-pointer":"","appearance-none":"","gap-1":"","rounded-lg":"","rounded-md":"","border-none":"","p-2":"","outline-none":""},[At(z("input",{"onUpdate:modelValue":x[2]||(x[2]=I=>o.value=I),checked:o.value,"aria-checked":o.value,name:"showLive2DViewerInspector",type:"checkbox",hidden:"","appearance-none":"","outline-none":""},null,8,Yf),[[Jr,o.value]]),x[16]||(x[16]=z("div",{"select-none":""},[z("div",{"i-solar:bug-bold-duotone":""})],-1))],2)]),ke(ci,null,{default:Be(()=>[o.value?(ee(),ie("div",Kf,[z("div",Wf,[z("div",Xf,[z("span",null,ge(H(d)("stage.viewers.debug-menu.vrm.model.title")),1)]),ke(Oi,{"h-fit":"","w-full":"",flex:"~ col",border:"~ gray/25 rounded-lg",divide:"y dashed gray/25","of-clip":"","shadow-sm":""},{label:Be(()=>[z("span",Qf,ge(H(d)("stage.viewers.debug-menu.vrm.camera")),1)]),default:Be(()=>[z("div",Zf,[x[17]||(x[17]=z("div",{text:"zinc-400 dark:zinc-500"},[z("span",null,"X")],-1)),z("label",Jf,[ke(jt,{modelValue:a.value,"onUpdate:modelValue":x[3]||(x[3]=I=>a.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),z("div",ed,[z("span",null,ge(a.value),1)]),x[18]||(x[18]=z("div",{text:"zinc-400 dark:zinc-500"},[z("span",null,"Y")],-1)),z("label",td,[ke(jt,{modelValue:s.value,"onUpdate:modelValue":x[4]||(x[4]=I=>s.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),z("div",nd,[z("span",null,ge(s.value),1)]),x[19]||(x[19]=z("div",{text:"zinc-400 dark:zinc-500"},[z("span",null,"Z")],-1)),z("label",rd,[ke(jt,{modelValue:l.value,"onUpdate:modelValue":x[5]||(x[5]=I=>l.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),z("div",id,[z("span",null,ge(l.value),1)])])]),_:1}),ke(Oi,{"h-fit":"","w-full":"",flex:"~ col",border:"~ gray/25 rounded-lg",divide:"y dashed gray/25","of-clip":"","shadow-sm":""},{label:Be(()=>[z("span",od,ge(H(d)("stage.viewers.debug-menu.vrm.model.title")),1)]),default:Be(()=>[z("div",ad,[x[20]||(x[20]=z("div",{text:"zinc-400 dark:zinc-500"},[z("span",null,"X")],-1)),z("label",sd,[ke(jt,{modelValue:u.value,"onUpdate:modelValue":x[6]||(x[6]=I=>u.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),z("div",ld,[z("span",null,ge(u.value),1)]),x[21]||(x[21]=z("div",{text:"zinc-400 dark:zinc-500"},[z("span",null,"Y")],-1)),z("label",ud,[ke(jt,{modelValue:c.value,"onUpdate:modelValue":x[7]||(x[7]=I=>c.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),z("div",cd,[z("span",null,ge(c.value),1)]),x[22]||(x[22]=z("div",{text:"zinc-400 dark:zinc-500"},[z("span",null,"Z")],-1)),z("label",fd,[ke(jt,{modelValue:f.value,"onUpdate:modelValue":x[8]||(x[8]=I=>f.value=I),min:-10,max:10,step:.01},null,8,["modelValue"])]),z("div",dd,[z("span",null,ge(f.value),1)])])]),_:1}),z("div",pd,[z("span",null,ge(H(d)("stage.viewers.debug-menu.emotions")),1)]),z("div",hd,[z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[9]||(x[9]=I=>{var A;return(A=p.value)==null?void 0:A.setExpression("neutral")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.neutral")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[10]||(x[10]=I=>{var A;return(A=p.value)==null?void 0:A.setExpression("surprised")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.surprised")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[11]||(x[11]=I=>{var A;return(A=p.value)==null?void 0:A.setExpression("sad")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.sad")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[12]||(x[12]=I=>{var A;return(A=p.value)==null?void 0:A.setExpression("angry")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.angry")),1),z("button",{"rounded-lg":"",bg:"zinc-100/70 dark:zinc-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:x[13]||(x[13]=I=>{var A;return(A=p.value)==null?void 0:A.setExpression("happy")})},ge(H(d)("stage.viewers.debug-menu.emotions-btn.happy")),1)])])])):it("",!0)]),_:1})])]),_:1}))}}),gd=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"];class bn{constructor(e,n,r){this.normal=n,this.property=e,r&&(this.space=r)}}bn.prototype.normal={};bn.prototype.property={};bn.prototype.space=void 0;function Ba(t,e){const n={},r={};for(const i of t)Object.assign(n,i.property),Object.assign(r,i.normal);return new bn(n,r,e)}function Hr(t){return t.toLowerCase()}class Ke{constructor(e,n){this.attribute=n,this.property=e}}Ke.prototype.attribute="";Ke.prototype.booleanish=!1;Ke.prototype.boolean=!1;Ke.prototype.commaOrSpaceSeparated=!1;Ke.prototype.commaSeparated=!1;Ke.prototype.defined=!1;Ke.prototype.mustUseProperty=!1;Ke.prototype.number=!1;Ke.prototype.overloadedBoolean=!1;Ke.prototype.property="";Ke.prototype.spaceSeparated=!1;Ke.prototype.space=void 0;let yd=0;const fe=Ft(),Le=Ft(),Ua=Ft(),$=Ft(),Re=Ft(),Kt=Ft(),Qe=Ft();function Ft(){return 2**++yd}const Gr=Object.freeze(Object.defineProperty({__proto__:null,boolean:fe,booleanish:Le,commaOrSpaceSeparated:Qe,commaSeparated:Kt,number:$,overloadedBoolean:Ua,spaceSeparated:Re},Symbol.toStringTag,{value:"Module"})),br=Object.keys(Gr);class hi extends Ke{constructor(e,n,r,i){let o=-1;if(super(e,n),mo(this,"space",i),typeof r=="number")for(;++o4&&n.slice(0,4)==="data"&&wd.test(e)){if(e.charAt(4)==="-"){const o=e.slice(5).replace(go,_d);r="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=e.slice(4);if(!go.test(o)){let a=o.replace(bd,kd);a.charAt(0)!=="-"&&(a="-"+a),e="data"+a}}i=hi}return new i(r,e)}function kd(t){return"-"+t.toLowerCase()}function _d(t){return t.charAt(1).toUpperCase()}const Ad=Ba([ja,xd,Ga,$a,qa],"html"),Ya=Ba([ja,vd,Ga,$a,qa],"svg"),yo={}.hasOwnProperty;function Ed(t,e){const n=e||{};function r(i,...o){let a=r.invalid;const s=r.handlers;if(i&&yo.call(i,t)){const l=String(i[t]);a=yo.call(s,l)?s[l]:r.unknown}if(a)return a.call(this,i,...o)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}const Md=/^>|^->||--!>|"],Id=["<",">"];function Rd(t,e,n,r){return r.settings.bogusComments?"":"";function i(o){return qt(o,Object.assign({},r.settings.characterReferences,{subset:Id}))}}function Cd(t,e,n,r){return""}function Nd(t,e){const n=e||{};return(t[t.length-1]===""?[...t,""]:t).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}function Ld(t){return t.join(" ").trim()}const Pd=/[ \t\n\f\r]/g;function mi(t){return typeof t=="object"?t.type==="text"?xo(t.value):!1:xo(t)}function xo(t){return t.replace(Pd,"")===""}const De=Wa(1),Ka=Wa(-1),Dd=[];function Wa(t){return e;function e(n,r,i){const o=n?n.children:Dd;let a=(r||0)+t,s=o[a];if(!i)for(;s&&mi(s);)a+=t,s=o[a];return s}}const Od={}.hasOwnProperty;function Xa(t){return e;function e(n,r,i){return Od.call(t,n.tagName)&&t[n.tagName](n,r,i)}}const gi=Xa({body:Fd,caption:wr,colgroup:wr,dd:Vd,dt:jd,head:wr,html:zd,li:Ud,optgroup:Hd,option:Gd,p:Bd,rp:vo,rt:vo,tbody:qd,td:bo,tfoot:Yd,th:bo,thead:$d,tr:Kd});function wr(t,e,n){const r=De(n,e,!0);return!r||r.type!=="comment"&&!(r.type==="text"&&mi(r.value.charAt(0)))}function zd(t,e,n){const r=De(n,e);return!r||r.type!=="comment"}function Fd(t,e,n){const r=De(n,e);return!r||r.type!=="comment"}function Bd(t,e,n){const r=De(n,e);return r?r.type==="element"&&(r.tagName==="address"||r.tagName==="article"||r.tagName==="aside"||r.tagName==="blockquote"||r.tagName==="details"||r.tagName==="div"||r.tagName==="dl"||r.tagName==="fieldset"||r.tagName==="figcaption"||r.tagName==="figure"||r.tagName==="footer"||r.tagName==="form"||r.tagName==="h1"||r.tagName==="h2"||r.tagName==="h3"||r.tagName==="h4"||r.tagName==="h5"||r.tagName==="h6"||r.tagName==="header"||r.tagName==="hgroup"||r.tagName==="hr"||r.tagName==="main"||r.tagName==="menu"||r.tagName==="nav"||r.tagName==="ol"||r.tagName==="p"||r.tagName==="pre"||r.tagName==="section"||r.tagName==="table"||r.tagName==="ul"):!n||!(n.type==="element"&&(n.tagName==="a"||n.tagName==="audio"||n.tagName==="del"||n.tagName==="ins"||n.tagName==="map"||n.tagName==="noscript"||n.tagName==="video"))}function Ud(t,e,n){const r=De(n,e);return!r||r.type==="element"&&r.tagName==="li"}function jd(t,e,n){const r=De(n,e);return!!(r&&r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd"))}function Vd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="dt"||r.tagName==="dd")}function vo(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="rp"||r.tagName==="rt")}function Hd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&r.tagName==="optgroup"}function Gd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="option"||r.tagName==="optgroup")}function $d(t,e,n){const r=De(n,e);return!!(r&&r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot"))}function qd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="tbody"||r.tagName==="tfoot")}function Yd(t,e,n){return!De(n,e)}function Kd(t,e,n){const r=De(n,e);return!r||r.type==="element"&&r.tagName==="tr"}function bo(t,e,n){const r=De(n,e);return!r||r.type==="element"&&(r.tagName==="td"||r.tagName==="th")}const Wd=Xa({body:Zd,colgroup:Jd,head:Qd,html:Xd,tbody:ep});function Xd(t){const e=De(t,-1);return!e||e.type!=="comment"}function Qd(t){const e=new Set;for(const r of t.children)if(r.type==="element"&&(r.tagName==="base"||r.tagName==="title")){if(e.has(r.tagName))return!1;e.add(r.tagName)}const n=t.children[0];return!n||n.type==="element"}function Zd(t){const e=De(t,-1,!0);return!e||e.type!=="comment"&&!(e.type==="text"&&mi(e.value.charAt(0)))&&!(e.type==="element"&&(e.tagName==="meta"||e.tagName==="link"||e.tagName==="script"||e.tagName==="style"||e.tagName==="template"))}function Jd(t,e,n){const r=Ka(n,e),i=De(t,-1,!0);return n&&r&&r.type==="element"&&r.tagName==="colgroup"&&gi(r,n.children.indexOf(r),n)?!1:!!(i&&i.type==="element"&&i.tagName==="col")}function ep(t,e,n){const r=Ka(n,e),i=De(t,-1);return n&&r&&r.type==="element"&&(r.tagName==="thead"||r.tagName==="tbody")&&gi(r,n.children.indexOf(r),n)?!1:!!(i&&i.type==="element"&&i.tagName==="tr")}const In={name:[[` \f\r &/=>`.split(""),` \f\r "&'/=>\``.split("")],[`\0 \f\r "&'/<=>`.split(""),`\0 @@ -519,18 +519,18 @@ void main() { \f\r &>`.split(""),`\0 \f\r "&'<=>\``.split("")],[`\0 \f\r "&'<=>\``.split(""),`\0 -\f\r "&'<=>\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function tp(t,e,n,r){const i=r.schema,o=i.space==="svg"?!1:r.settings.omitOptionalTags;let s=i.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(t.tagName.toLowerCase());const a=[];let l;i.space==="html"&&t.tagName==="svg"&&(r.schema=qs);const u=np(r,t.properties),c=r.all(i.space==="html"&&t.tagName==="template"?t.content:t);return r.schema=i,c&&(s=!1),(u||!o||!Wd(t,e,n))&&(a.push("<",t.tagName,u?" "+u:""),s&&(i.space==="svg"||r.settings.closeSelfClosing)&&(l=u.charAt(u.length-1),(!r.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&a.push(" "),a.push("/")),a.push(">")),a.push(c),!s&&(!o||!gi(t,e,n))&&a.push(""),a.join("")}function np(t,e){const n=[];let r=-1,i;if(e){for(i in e)if(e[i]!==null&&e[i]!==void 0){const o=rp(t,i,e[i]);o&&n.push(o)}}for(;++rDi(n,t.alternative)&&(s=t.alternative),a=s+Yt(n,Object.assign({},t.settings.characterReferences,{subset:(s==="'"?In.single:In.double)[i][o],attribute:!0}))+s),l+(a&&"="+a))}const ip=["<","&"];function Qs(t,e,n,r){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?t.value:Yt(t.value,Object.assign({},r.settings.characterReferences,{subset:ip}))}function op(t,e,n,r){return r.settings.allowDangerousHtml?t.value:Qs(t,e,n,r)}function sp(t,e,n,r){return r.all(t)}const ap=Ed("type",{invalid:lp,unknown:up,handlers:{comment:Rd,doctype:Cd,element:tp,raw:op,root:sp,text:Qs}});function lp(t){throw new Error("Expected node, not `"+t+"`")}function up(t){const e=t;throw new Error("Cannot compile unknown node `"+e.type+"`")}const cp={},fp={},dp=[];function pp(t,e){const n=e||cp,r=n.quote||'"',i=r==='"'?"'":'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:hp,all:mp,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||gd,characterReferences:n.characterReferences||fp,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?qs:_d,quote:r,alternative:i}.one(Array.isArray(t)?{type:"root",children:t}:t,void 0,void 0)}function hp(t,e,n){return ap(t,e,n,this)}function mp(t){const e=[],n=t&&t.children||dp;let r=-1;for(;++ri?0:i+e:e=e>i?i:e,n=n>0?n:0,r.length<1e4)s=Array.from(r),s.unshift(e,n),t.splice(...s);else for(n&&t.splice(e,n);o0?(ct(t,t.length,0,e),t):e}const ko={}.hasOwnProperty;function bp(t){const e={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Wt(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ut=It(/[A-Za-z]/),et=It(/[\dA-Za-z]/),kp=It(/[#-'*+\--9=?A-Z^-~]/);function $r(t){return t!==null&&(t<32||t===127)}const Yr=It(/\d/),Ap=It(/[\dA-Fa-f]/),_p=It(/[!-/:-@[-`{-~]/);function ae(t){return t!==null&&t<-2}function qe(t){return t!==null&&(t<0||t===32)}function _e(t){return t===-2||t===-1||t===32}const Ep=It(new RegExp("\\p{P}|\\p{S}","u")),Mp=It(/\s/);function It(t){return e;function e(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function Jt(t){const e=[];let n=-1,r=0,i=0;for(;++n55295&&o<57344){const a=t.charCodeAt(n+1);o<56320&&a>56319&&a<57344?(s=String.fromCharCode(o,a),i=1):s="�"}else s=String.fromCharCode(o);s&&(e.push(t.slice(r,n),encodeURIComponent(s)),r=n+i+1,s=""),i&&(n+=i,i=0)}return e.join("")+t.slice(r)}function Ce(t,e,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let o=0;return s;function s(l){return _e(l)?(t.enter(n),a(l)):e(l)}function a(l){return _e(l)&&o++s))return;const M=e.events.length;let y=M,g,m;for(;y--;)if(e.events[y][0]==="exit"&&e.events[y][1].type==="chunkFlow"){if(g){m=e.events[y][1].end;break}g=!0}for(T(r),h=M;h_;){const P=n[C];e.containerState=P[1],P[0].exit.call(e,t)}n.length=_}function I(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function Np(t,e,n){return Ce(t,t.attempt(this.parser.constructs.document,e,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function _o(t){if(t===null||qe(t)||Mp(t))return 1;if(Ep(t))return 2}function xi(t,e,n){const r=[];let i=-1;for(;++i1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;const f={...t[r][1].end},p={...t[n][1].start};Eo(f,-l),Eo(p,l),s={type:l>1?"strongSequence":"emphasisSequence",start:f,end:{...t[r][1].end}},a={type:l>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:p},o={type:l>1?"strongText":"emphasisText",start:{...t[r][1].end},end:{...t[n][1].start}},i={type:l>1?"strong":"emphasis",start:{...s.start},end:{...a.end}},t[r][1].end={...s.start},t[n][1].start={...a.end},u=[],t[r][1].end.offset-t[r][1].start.offset&&(u=rt(u,[["enter",t[r][1],e],["exit",t[r][1],e]])),u=rt(u,[["enter",i,e],["enter",s,e],["exit",s,e],["enter",o,e]]),u=rt(u,xi(e.parser.constructs.insideSpan.null,t.slice(r+1,n),e)),u=rt(u,[["exit",o,e],["enter",a,e],["exit",a,e],["exit",i,e]]),t[n][1].end.offset-t[n][1].start.offset?(c=2,u=rt(u,[["enter",t[n][1],e],["exit",t[n][1],e]])):c=0,ct(t,r-1,n-r+3,u),n=r+u.length-c-2;break}}for(n=-1;++n0&&_e(h)?Ce(t,I,"linePrefix",o+1)(h):I(h)}function I(h){return h===null||ae(h)?t.check(Mo,x,C)(h):(t.enter("codeFlowValue"),_(h))}function _(h){return h===null||ae(h)?(t.exit("codeFlowValue"),I(h)):(t.consume(h),_)}function C(h){return t.exit("codeFenced"),e(h)}function P(h,M,y){let g=0;return m;function m(D){return h.enter("lineEnding"),h.consume(D),h.exit("lineEnding"),k}function k(D){return h.enter("codeFencedFence"),_e(D)?Ce(h,E,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):E(D)}function E(D){return D===a?(h.enter("codeFencedFenceSequence"),O(D)):y(D)}function O(D){return D===a?(g++,h.consume(D),O):g>=s?(h.exit("codeFencedFenceSequence"),_e(D)?Ce(h,z,"whitespace")(D):z(D)):y(D)}function z(D){return D===null||ae(D)?(h.exit("codeFencedFence"),M(D)):y(D)}}}function Gp(t,e,n){const r=this;return i;function i(s){return s===null?n(s):(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}const Tr={name:"codeIndented",tokenize:Yp},$p={partial:!0,tokenize:qp};function Yp(t,e,n){const r=this;return i;function i(u){return t.enter("codeIndented"),Ce(t,o,"linePrefix",5)(u)}function o(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?s(u):n(u)}function s(u){return u===null?l(u):ae(u)?t.attempt($p,s,l)(u):(t.enter("codeFlowValue"),a(u))}function a(u){return u===null||ae(u)?(t.exit("codeFlowValue"),s(u)):(t.consume(u),a)}function l(u){return t.exit("codeIndented"),e(u)}}function qp(t,e,n){const r=this;return i;function i(s){return r.parser.lazy[r.now().line]?n(s):ae(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),i):Ce(t,o,"linePrefix",5)(s)}function o(s){const a=r.events[r.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?e(s):ae(s)?i(s):n(s)}}const Kp={name:"codeText",previous:Xp,resolve:Wp,tokenize:Qp};function Wp(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length)return this.right.slice(this.right.length-r+this.left.length,this.right.length-e+this.left.length).reverse();const i=this.left.slice(e);return i.push(...this.right.slice(this.right.length-r+this.left.length).reverse()),i}splice(e,n,r){const i=n||0;this.setCursor(Math.trunc(e));const o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&an(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),an(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),an(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?e(s):t.interrupt(r.parser.constructs.flow,n,e)(s)}}function ia(t,e,n,r,i,o,s,a,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return f;function f(T){return T===60?(t.enter(r),t.enter(i),t.enter(o),t.consume(T),t.exit(o),p):T===null||T===32||T===41||$r(T)?n(T):(t.enter(r),t.enter(s),t.enter(a),t.enter("chunkString",{contentType:"string"}),x(T))}function p(T){return T===62?(t.enter(o),t.consume(T),t.exit(o),t.exit(i),t.exit(r),e):(t.enter(a),t.enter("chunkString",{contentType:"string"}),d(T))}function d(T){return T===62?(t.exit("chunkString"),t.exit(a),p(T)):T===null||T===60||ae(T)?n(T):(t.consume(T),T===92?b:d)}function b(T){return T===60||T===62||T===92?(t.consume(T),d):d(T)}function x(T){return!c&&(T===null||T===41||qe(T))?(t.exit("chunkString"),t.exit(a),t.exit(s),t.exit(r),e(T)):c999||d===null||d===91||d===93&&!l||d===94&&!a&&"_hiddenFootnoteSupport"in s.parser.constructs?n(d):d===93?(t.exit(o),t.enter(i),t.consume(d),t.exit(i),t.exit(r),e):ae(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),c):(t.enter("chunkString",{contentType:"string"}),f(d))}function f(d){return d===null||d===91||d===93||ae(d)||a++>999?(t.exit("chunkString"),c(d)):(t.consume(d),l||(l=!_e(d)),d===92?p:f)}function p(d){return d===91||d===92||d===93?(t.consume(d),a++,f):f(d)}}function sa(t,e,n,r,i,o){let s;return a;function a(p){return p===34||p===39||p===40?(t.enter(r),t.enter(i),t.consume(p),t.exit(i),s=p===40?41:p,l):n(p)}function l(p){return p===s?(t.enter(i),t.consume(p),t.exit(i),t.exit(r),e):(t.enter(o),u(p))}function u(p){return p===s?(t.exit(o),l(s)):p===null?n(p):ae(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),Ce(t,u,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===s||p===null||ae(p)?(t.exit("chunkString"),u(p)):(t.consume(p),p===92?f:c)}function f(p){return p===s||p===92?(t.consume(p),c):c(p)}}function fn(t,e){let n;return r;function r(i){return ae(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),n=!0,r):_e(i)?Ce(t,r,n?"linePrefix":"lineSuffix")(i):e(i)}}const oh={name:"definition",tokenize:ah},sh={partial:!0,tokenize:lh};function ah(t,e,n){const r=this;let i;return o;function o(d){return t.enter("definition"),s(d)}function s(d){return oa.call(r,t,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(d)}function a(d){return i=Wt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),d===58?(t.enter("definitionMarker"),t.consume(d),t.exit("definitionMarker"),l):n(d)}function l(d){return qe(d)?fn(t,u)(d):u(d)}function u(d){return ia(t,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(d)}function c(d){return t.attempt(sh,f,f)(d)}function f(d){return _e(d)?Ce(t,p,"whitespace")(d):p(d)}function p(d){return d===null||ae(d)?(t.exit("definition"),r.parser.defined.push(i),e(d)):n(d)}}function lh(t,e,n){return r;function r(a){return qe(a)?fn(t,i)(a):n(a)}function i(a){return sa(t,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function o(a){return _e(a)?Ce(t,s,"whitespace")(a):s(a)}function s(a){return a===null||ae(a)?e(a):n(a)}}const uh={name:"hardBreakEscape",tokenize:ch};function ch(t,e,n){return r;function r(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return ae(o)?(t.exit("hardBreakEscape"),e(o)):n(o)}}const fh={name:"headingAtx",resolve:dh,tokenize:ph};function dh(t,e){let n=t.length-2,r=3,i,o;return t[r][1].type==="whitespace"&&(r+=2),n-2>r&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&t[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:t[r][1].start,end:t[n][1].end},o={type:"chunkText",start:t[r][1].start,end:t[n][1].end,contentType:"text"},ct(t,r,n-r+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function ph(t,e,n){let r=0;return i;function i(c){return t.enter("atxHeading"),o(c)}function o(c){return t.enter("atxHeadingSequence"),s(c)}function s(c){return c===35&&r++<6?(t.consume(c),s):c===null||qe(c)?(t.exit("atxHeadingSequence"),a(c)):n(c)}function a(c){return c===35?(t.enter("atxHeadingSequence"),l(c)):c===null||ae(c)?(t.exit("atxHeading"),e(c)):_e(c)?Ce(t,a,"whitespace")(c):(t.enter("atxHeadingText"),u(c))}function l(c){return c===35?(t.consume(c),l):(t.exit("atxHeadingSequence"),a(c))}function u(c){return c===null||c===35||qe(c)?(t.exit("atxHeadingText"),a(c)):(t.consume(c),u)}}const hh=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Io=["pre","script","style","textarea"],mh={concrete:!0,name:"htmlFlow",resolveTo:xh,tokenize:vh},gh={partial:!0,tokenize:wh},yh={partial:!0,tokenize:bh};function xh(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function vh(t,e,n){const r=this;let i,o,s,a,l;return u;function u(R){return c(R)}function c(R){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(R),f}function f(R){return R===33?(t.consume(R),p):R===47?(t.consume(R),o=!0,x):R===63?(t.consume(R),i=3,r.interrupt?e:A):ut(R)?(t.consume(R),s=String.fromCharCode(R),v):n(R)}function p(R){return R===45?(t.consume(R),i=2,d):R===91?(t.consume(R),i=5,a=0,b):ut(R)?(t.consume(R),i=4,r.interrupt?e:A):n(R)}function d(R){return R===45?(t.consume(R),r.interrupt?e:A):n(R)}function b(R){const pe="CDATA[";return R===pe.charCodeAt(a++)?(t.consume(R),a===pe.length?r.interrupt?e:E:b):n(R)}function x(R){return ut(R)?(t.consume(R),s=String.fromCharCode(R),v):n(R)}function v(R){if(R===null||R===47||R===62||qe(R)){const pe=R===47,ye=s.toLowerCase();return!pe&&!o&&Io.includes(ye)?(i=1,r.interrupt?e(R):E(R)):hh.includes(s.toLowerCase())?(i=6,pe?(t.consume(R),T):r.interrupt?e(R):E(R)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(R):o?I(R):_(R))}return R===45||et(R)?(t.consume(R),s+=String.fromCharCode(R),v):n(R)}function T(R){return R===62?(t.consume(R),r.interrupt?e:E):n(R)}function I(R){return _e(R)?(t.consume(R),I):m(R)}function _(R){return R===47?(t.consume(R),m):R===58||R===95||ut(R)?(t.consume(R),C):_e(R)?(t.consume(R),_):m(R)}function C(R){return R===45||R===46||R===58||R===95||et(R)?(t.consume(R),C):P(R)}function P(R){return R===61?(t.consume(R),h):_e(R)?(t.consume(R),P):_(R)}function h(R){return R===null||R===60||R===61||R===62||R===96?n(R):R===34||R===39?(t.consume(R),l=R,M):_e(R)?(t.consume(R),h):y(R)}function M(R){return R===l?(t.consume(R),l=null,g):R===null||ae(R)?n(R):(t.consume(R),M)}function y(R){return R===null||R===34||R===39||R===47||R===60||R===61||R===62||R===96||qe(R)?P(R):(t.consume(R),y)}function g(R){return R===47||R===62||_e(R)?_(R):n(R)}function m(R){return R===62?(t.consume(R),k):n(R)}function k(R){return R===null||ae(R)?E(R):_e(R)?(t.consume(R),k):n(R)}function E(R){return R===45&&i===2?(t.consume(R),B):R===60&&i===1?(t.consume(R),X):R===62&&i===4?(t.consume(R),te):R===63&&i===3?(t.consume(R),A):R===93&&i===5?(t.consume(R),Q):ae(R)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(gh,ce,O)(R)):R===null||ae(R)?(t.exit("htmlFlowData"),O(R)):(t.consume(R),E)}function O(R){return t.check(yh,z,ce)(R)}function z(R){return t.enter("lineEnding"),t.consume(R),t.exit("lineEnding"),D}function D(R){return R===null||ae(R)?O(R):(t.enter("htmlFlowData"),E(R))}function B(R){return R===45?(t.consume(R),A):E(R)}function X(R){return R===47?(t.consume(R),s="",Z):E(R)}function Z(R){if(R===62){const pe=s.toLowerCase();return Io.includes(pe)?(t.consume(R),te):E(R)}return ut(R)&&s.length<8?(t.consume(R),s+=String.fromCharCode(R),Z):E(R)}function Q(R){return R===93?(t.consume(R),A):E(R)}function A(R){return R===62?(t.consume(R),te):R===45&&i===2?(t.consume(R),A):E(R)}function te(R){return R===null||ae(R)?(t.exit("htmlFlowData"),ce(R)):(t.consume(R),te)}function ce(R){return t.exit("htmlFlow"),e(R)}}function bh(t,e,n){const r=this;return i;function i(s){return ae(s)?(t.enter("lineEnding"),t.consume(s),t.exit("lineEnding"),o):n(s)}function o(s){return r.parser.lazy[r.now().line]?n(s):e(s)}}function wh(t,e,n){return r;function r(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(Qn,e,n)}}const Th={name:"htmlText",tokenize:kh};function kh(t,e,n){const r=this;let i,o,s;return a;function a(A){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(A),l}function l(A){return A===33?(t.consume(A),u):A===47?(t.consume(A),P):A===63?(t.consume(A),_):ut(A)?(t.consume(A),y):n(A)}function u(A){return A===45?(t.consume(A),c):A===91?(t.consume(A),o=0,b):ut(A)?(t.consume(A),I):n(A)}function c(A){return A===45?(t.consume(A),d):n(A)}function f(A){return A===null?n(A):A===45?(t.consume(A),p):ae(A)?(s=f,X(A)):(t.consume(A),f)}function p(A){return A===45?(t.consume(A),d):f(A)}function d(A){return A===62?B(A):A===45?p(A):f(A)}function b(A){const te="CDATA[";return A===te.charCodeAt(o++)?(t.consume(A),o===te.length?x:b):n(A)}function x(A){return A===null?n(A):A===93?(t.consume(A),v):ae(A)?(s=x,X(A)):(t.consume(A),x)}function v(A){return A===93?(t.consume(A),T):x(A)}function T(A){return A===62?B(A):A===93?(t.consume(A),T):x(A)}function I(A){return A===null||A===62?B(A):ae(A)?(s=I,X(A)):(t.consume(A),I)}function _(A){return A===null?n(A):A===63?(t.consume(A),C):ae(A)?(s=_,X(A)):(t.consume(A),_)}function C(A){return A===62?B(A):_(A)}function P(A){return ut(A)?(t.consume(A),h):n(A)}function h(A){return A===45||et(A)?(t.consume(A),h):M(A)}function M(A){return ae(A)?(s=M,X(A)):_e(A)?(t.consume(A),M):B(A)}function y(A){return A===45||et(A)?(t.consume(A),y):A===47||A===62||qe(A)?g(A):n(A)}function g(A){return A===47?(t.consume(A),B):A===58||A===95||ut(A)?(t.consume(A),m):ae(A)?(s=g,X(A)):_e(A)?(t.consume(A),g):B(A)}function m(A){return A===45||A===46||A===58||A===95||et(A)?(t.consume(A),m):k(A)}function k(A){return A===61?(t.consume(A),E):ae(A)?(s=k,X(A)):_e(A)?(t.consume(A),k):g(A)}function E(A){return A===null||A===60||A===61||A===62||A===96?n(A):A===34||A===39?(t.consume(A),i=A,O):ae(A)?(s=E,X(A)):_e(A)?(t.consume(A),E):(t.consume(A),z)}function O(A){return A===i?(t.consume(A),i=void 0,D):A===null?n(A):ae(A)?(s=O,X(A)):(t.consume(A),O)}function z(A){return A===null||A===34||A===39||A===60||A===61||A===96?n(A):A===47||A===62||qe(A)?g(A):(t.consume(A),z)}function D(A){return A===47||A===62||qe(A)?g(A):n(A)}function B(A){return A===62?(t.consume(A),t.exit("htmlTextData"),t.exit("htmlText"),e):n(A)}function X(A){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(A),t.exit("lineEnding"),Z}function Z(A){return _e(A)?Ce(t,Q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):Q(A)}function Q(A){return t.enter("htmlTextData"),s(A)}}const vi={name:"labelEnd",resolveAll:Mh,resolveTo:Sh,tokenize:Ih},Ah={tokenize:Rh},_h={tokenize:Ch},Eh={tokenize:Nh};function Mh(t){let e=-1;const n=[];for(;++e=3&&(u===null||ae(u))?(t.exit("thematicBreak"),e(u)):n(u)}function l(u){return u===i?(t.consume(u),r++,l):(t.exit("thematicBreakSequence"),_e(u)?Ce(t,a,"whitespace")(u):a(u))}}const Ye={continuation:{tokenize:Vh},exit:Gh,name:"list",tokenize:jh},Bh={partial:!0,tokenize:$h},Uh={partial:!0,tokenize:Hh};function jh(t,e,n){const r=this,i=r.events[r.events.length-1];let o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,s=0;return a;function a(d){const b=r.containerState.type||(d===42||d===43||d===45?"listUnordered":"listOrdered");if(b==="listUnordered"?!r.containerState.marker||d===r.containerState.marker:Yr(d)){if(r.containerState.type||(r.containerState.type=b,t.enter(b,{_container:!0})),b==="listUnordered")return t.enter("listItemPrefix"),d===42||d===45?t.check(Dn,n,u)(d):u(d);if(!r.interrupt||d===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(d)}return n(d)}function l(d){return Yr(d)&&++s<10?(t.consume(d),l):(!r.interrupt||s<2)&&(r.containerState.marker?d===r.containerState.marker:d===41||d===46)?(t.exit("listItemValue"),u(d)):n(d)}function u(d){return t.enter("listItemMarker"),t.consume(d),t.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||d,t.check(Qn,r.interrupt?n:c,t.attempt(Bh,p,f))}function c(d){return r.containerState.initialBlankLine=!0,o++,p(d)}function f(d){return _e(d)?(t.enter("listItemPrefixWhitespace"),t.consume(d),t.exit("listItemPrefixWhitespace"),p):n(d)}function p(d){return r.containerState.size=o+r.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(d)}}function Vh(t,e,n){const r=this;return r.containerState._closeFlow=void 0,t.check(Qn,i,o);function i(a){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Ce(t,e,"listItemIndent",r.containerState.size+1)(a)}function o(a){return r.containerState.furtherBlankLines||!_e(a)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s(a)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,t.attempt(Uh,e,s)(a))}function s(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,Ce(t,t.attempt(Ye,e,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function Hh(t,e,n){const r=this;return Ce(t,i,"listItemIndent",r.containerState.size+1);function i(o){const s=r.events[r.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===r.containerState.size?e(o):n(o)}}function Gh(t){t.exit(this.containerState.type)}function $h(t,e,n){const r=this;return Ce(t,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){const s=r.events[r.events.length-1];return!_e(o)&&s&&s[1].type==="listItemPrefixWhitespace"?e(o):n(o)}}const Ro={name:"setextUnderline",resolveTo:Yh,tokenize:qh};function Yh(t,e){let n=t.length,r,i,o;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){r=n;break}t[n][1].type==="paragraph"&&(i=n)}else t[n][1].type==="content"&&t.splice(n,1),!o&&t[n][1].type==="definition"&&(o=n);const s={type:"setextHeading",start:{...t[i][1].start},end:{...t[t.length-1][1].end}};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",s,e]),t.splice(o+1,0,["exit",t[r][1],e]),t[r][1].end={...t[o][1].end}):t[r][1]=s,t.push(["exit",s,e]),t}function qh(t,e,n){const r=this;let i;return o;function o(u){let c=r.events.length,f;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){f=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||f)?(t.enter("setextHeadingLine"),i=u,s(u)):n(u)}function s(u){return t.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===i?(t.consume(u),a):(t.exit("setextHeadingLineSequence"),_e(u)?Ce(t,l,"lineSuffix")(u):l(u))}function l(u){return u===null||ae(u)?(t.exit("setextHeadingLine"),e(u)):n(u)}}const Kh={tokenize:Wh};function Wh(t){const e=this,n=t.attempt(Qn,r,t.attempt(this.parser.constructs.flowInitial,i,Ce(t,t.attempt(this.parser.constructs.flow,i,t.attempt(eh,i)),"linePrefix")));return n;function r(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,n}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,n}}const Xh={resolveAll:la()},Qh=aa("string"),Zh=aa("text");function aa(t){return{resolveAll:la(t==="text"?Jh:void 0),tokenize:e};function e(n){const r=this,i=this.parser.constructs[t],o=n.attempt(i,s,a);return s;function s(c){return u(c)?o(c):a(c)}function a(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),o(c)):(n.consume(c),l)}function u(c){if(c===null)return!0;const f=i[c];let p=-1;if(f)for(;++p-1){const a=s[0];typeof a=="string"?s[0]=a.slice(r):s.shift()}o>0&&s.push(t[i].slice(0,o))}return s}function dm(t,e){let n=-1;const r=[];let i;for(;++n0){const He=oe.tokenStack[oe.tokenStack.length-1];(He[1]||Po).call(oe,void 0,He[0])}for(K.position={start:kt(j.length>0?j[0][1].start:{line:1,column:1,offset:0}),end:kt(j.length>0?j[j.length-2][1].end:{line:1,column:1,offset:0})},we=-1;++we1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};t.patch(e,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return t.patch(e,u),t.applyData(e,u)}function Im(t,e){const n={type:"element",tagName:"h"+e.depth,properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function Rm(t,e){if(t.options.allowDangerousHtml){const n={type:"raw",value:e.value};return t.patch(e,n),t.applyData(e,n)}}function fa(t,e){const n=e.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(e.label||e.identifier)+"]"),e.type==="imageReference")return[{type:"text",value:"!["+e.alt+r}];const i=t.all(e),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});const s=i[i.length-1];return s&&s.type==="text"?s.value+=r:i.push({type:"text",value:r}),i}function Cm(t,e){const n=String(e.identifier).toUpperCase(),r=t.definitionById.get(n);if(!r)return fa(t,e);const i={src:Jt(r.url||""),alt:e.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const o={type:"element",tagName:"img",properties:i,children:[]};return t.patch(e,o),t.applyData(e,o)}function Nm(t,e){const n={src:Jt(e.url)};e.alt!==null&&e.alt!==void 0&&(n.alt=e.alt),e.title!==null&&e.title!==void 0&&(n.title=e.title);const r={type:"element",tagName:"img",properties:n,children:[]};return t.patch(e,r),t.applyData(e,r)}function Lm(t,e){const n={type:"text",value:e.value.replace(/\r?\n|\r/g," ")};t.patch(e,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return t.patch(e,r),t.applyData(e,r)}function Pm(t,e){const n=String(e.identifier).toUpperCase(),r=t.definitionById.get(n);if(!r)return fa(t,e);const i={href:Jt(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const o={type:"element",tagName:"a",properties:i,children:t.all(e)};return t.patch(e,o),t.applyData(e,o)}function Dm(t,e){const n={href:Jt(e.url)};e.title!==null&&e.title!==void 0&&(n.title=e.title);const r={type:"element",tagName:"a",properties:n,children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Om(t,e,n){const r=t.all(e),i=n?Fm(n):da(e),o={},s=[];if(typeof e.checked=="boolean"){const c=r[0];let f;c&&c.type==="element"&&c.tagName==="p"?f=c:(f={type:"element",tagName:"p",properties:{},children:[]},r.unshift(f)),f.children.length>0&&f.children.unshift({type:"text",value:" "}),f.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:e.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let a=-1;for(;++a1}function zm(t,e){const n={},r=t.all(e);let i=-1;for(typeof e.start=="number"&&e.start!==1&&(n.start=e.start);++i0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Vm(t){const e=ha(t),n=pa(t);if(e&&n)return{start:e,end:n}}function Hm(t,e){const n=t.all(e),r=n.shift(),i=[];if(r){const s={type:"element",tagName:"thead",properties:{},children:t.wrap([r],!0)};t.patch(e.children[0],s),i.push(s)}if(n.length>0){const s={type:"element",tagName:"tbody",properties:{},children:t.wrap(n,!0)},a=ha(e.children[1]),l=pa(e.children[e.children.length-1]);a&&l&&(s.position={start:a,end:l}),i.push(s)}const o={type:"element",tagName:"table",properties:{},children:t.wrap(i,!0)};return t.patch(e,o),t.applyData(e,o)}function Gm(t,e,n){const r=n?n.children:void 0,o=(r?r.indexOf(e):1)===0?"th":"td",s=n&&n.type==="table"?n.align:void 0,a=s?s.length:e.children.length;let l=-1;const u=[];for(;++l0,!0),r[0]),i=r.index+r[0].length,r=n.exec(e);return o.push(Fo(e.slice(i),i>0,!1)),o.join("")}function Fo(t,e,n){let r=0,i=t.length;if(e){let o=t.codePointAt(r);for(;o===Do||o===Oo;)r++,o=t.codePointAt(r)}if(n){let o=t.codePointAt(i-1);for(;o===Do||o===Oo;)i--,o=t.codePointAt(i-1)}return i>r?t.slice(r,i):""}function qm(t,e){const n={type:"text",value:Ym(String(e.value))};return t.patch(e,n),t.applyData(e,n)}function Km(t,e){const n={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(e,n),t.applyData(e,n)}const Wm={blockquote:km,break:Am,code:_m,delete:Em,emphasis:Mm,footnoteReference:Sm,heading:Im,html:Rm,imageReference:Cm,image:Nm,inlineCode:Lm,linkReference:Pm,link:Dm,listItem:Om,list:zm,paragraph:Bm,root:Um,strong:jm,table:Hm,tableCell:$m,tableRow:Gm,text:qm,thematicBreak:Km,toml:Rn,yaml:Rn,definition:Rn,footnoteDefinition:Rn};function Rn(){}const ga=-1,Zn=0,Vn=1,Hn=2,bi=3,wi=4,Ti=5,ki=6,ya=7,xa=8,zo=typeof self=="object"?self:globalThis,Xm=(t,e)=>{const n=(i,o)=>(t.set(o,i),i),r=i=>{if(t.has(i))return t.get(i);const[o,s]=e[i];switch(o){case Zn:case ga:return n(s,i);case Vn:{const a=n([],i);for(const l of s)a.push(r(l));return a}case Hn:{const a=n({},i);for(const[l,u]of s)a[r(l)]=r(u);return a}case bi:return n(new Date(s),i);case wi:{const{source:a,flags:l}=s;return n(new RegExp(a,l),i)}case Ti:{const a=n(new Map,i);for(const[l,u]of s)a.set(r(l),r(u));return a}case ki:{const a=n(new Set,i);for(const l of s)a.add(r(l));return a}case ya:{const{name:a,message:l}=s;return n(new zo[a](l),i)}case xa:return n(BigInt(s),i);case"BigInt":return n(Object(BigInt(s)),i)}return n(new zo[o](s),i)};return r},Bo=t=>Xm(new Map,t)(0),Vt="",{toString:Qm}={},{keys:Zm}=Object,ln=t=>{const e=typeof t;if(e!=="object"||!t)return[Zn,e];const n=Qm.call(t).slice(8,-1);switch(n){case"Array":return[Vn,Vt];case"Object":return[Hn,Vt];case"Date":return[bi,Vt];case"RegExp":return[wi,Vt];case"Map":return[Ti,Vt];case"Set":return[ki,Vt]}return n.includes("Array")?[Vn,n]:n.includes("Error")?[ya,n]:[Hn,n]},Cn=([t,e])=>t===Zn&&(e==="function"||e==="symbol"),Jm=(t,e,n,r)=>{const i=(s,a)=>{const l=r.push(s)-1;return n.set(a,l),l},o=s=>{if(n.has(s))return n.get(s);let[a,l]=ln(s);switch(a){case Zn:{let c=s;switch(l){case"bigint":a=xa,c=s.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return i([ga],s)}return i([a,c],s)}case Vn:{if(l)return i([l,[...s]],s);const c=[],f=i([a,c],s);for(const p of s)c.push(o(p));return f}case Hn:{if(l)switch(l){case"BigInt":return i([l,s.toString()],s);case"Boolean":case"Number":case"String":return i([l,s.valueOf()],s)}if(e&&"toJSON"in s)return o(s.toJSON());const c=[],f=i([a,c],s);for(const p of Zm(s))(t||!Cn(ln(s[p])))&&c.push([o(p),o(s[p])]);return f}case bi:return i([a,s.toISOString()],s);case wi:{const{source:c,flags:f}=s;return i([a,{source:c,flags:f}],s)}case Ti:{const c=[],f=i([a,c],s);for(const[p,d]of s)(t||!(Cn(ln(p))||Cn(ln(d))))&&c.push([o(p),o(d)]);return f}case ki:{const c=[],f=i([a,c],s);for(const p of s)(t||!Cn(ln(p)))&&c.push(o(p));return f}}const{message:u}=s;return i([a,{name:l,message:u}],s)};return o},Uo=(t,{json:e,lossy:n}={})=>{const r=[];return Jm(!(e||n),!!e,new Map,r)(t),r},Gn=typeof structuredClone=="function"?(t,e)=>e&&("json"in e||"lossy"in e)?Bo(Uo(t,e)):structuredClone(t):(t,e)=>Bo(Uo(t,e));function eg(t,e){const n=[{type:"text",value:"↩"}];return e>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(e)}]}),n}function tg(t,e){return"Back to reference "+(t+1)+(e>1?"-"+e:"")}function ng(t){const e=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=t.options.footnoteBackContent||eg,r=t.options.footnoteBackLabel||tg,i=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",s=t.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let l=-1;for(;++l0&&b.push({type:"text",value:" "});let I=typeof n=="string"?n:n(l,d);typeof I=="string"&&(I={type:"text",value:I}),b.push({type:"element",tagName:"a",properties:{href:"#"+e+"fnref-"+p+(d>1?"-"+d:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(l,d),className:["data-footnote-backref"]},children:Array.isArray(I)?I:[I]})}const v=c[c.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const I=v.children[v.children.length-1];I&&I.type==="text"?I.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...b)}else c.push(...b);const T={type:"element",tagName:"li",properties:{id:e+"fn-"+p},children:t.wrap(c,!0)};t.patch(u,T),a.push(T)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Gn(s),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:` -`},{type:"element",tagName:"ol",properties:{},children:t.wrap(a,!0)},{type:"text",value:` -`}]}}const va=function(t){if(t==null)return sg;if(typeof t=="function")return Jn(t);if(typeof t=="object")return Array.isArray(t)?rg(t):ig(t);if(typeof t=="string")return og(t);throw new Error("Expected function, string, or object as test")};function rg(t){const e=[];let n=-1;for(;++n":""))+")"})}return p;function p(){let d=ba,b,x,v;if((!e||o(l,u,c[c.length-1]||void 0))&&(d=fg(n(l,c)),d[0]===jo))return d;if("children"in l&&l.children){const T=l;if(T.children&&d[0]!==ug)for(x=(r?T.children.length:-1)+s,v=c.concat(T);x>-1&&x\``.split("")]],single:[["&'".split(""),"\"&'`".split("")],["\0&'".split(""),"\0\"&'`".split("")]],double:[['"&'.split(""),"\"&'`".split("")],['\0"&'.split(""),"\0\"&'`".split("")]]};function tp(t,e,n,r){const i=r.schema,o=i.space==="svg"?!1:r.settings.omitOptionalTags;let a=i.space==="svg"?r.settings.closeEmptyElements:r.settings.voids.includes(t.tagName.toLowerCase());const s=[];let l;i.space==="html"&&t.tagName==="svg"&&(r.schema=Ya);const u=np(r,t.properties),c=r.all(i.space==="html"&&t.tagName==="template"?t.content:t);return r.schema=i,c&&(a=!1),(u||!o||!Wd(t,e,n))&&(s.push("<",t.tagName,u?" "+u:""),a&&(i.space==="svg"||r.settings.closeSelfClosing)&&(l=u.charAt(u.length-1),(!r.settings.tightSelfClosing||l==="/"||l&&l!=='"'&&l!=="'")&&s.push(" "),s.push("/")),s.push(">")),s.push(c),!a&&(!o||!gi(t,e,n))&&s.push(""),s.join("")}function np(t,e){const n=[];let r=-1,i;if(e){for(i in e)if(e[i]!==null&&e[i]!==void 0){const o=rp(t,i,e[i]);o&&n.push(o)}}for(;++rDi(n,t.alternative)&&(a=t.alternative),s=a+qt(n,Object.assign({},t.settings.characterReferences,{subset:(a==="'"?In.single:In.double)[i][o],attribute:!0}))+a),l+(s&&"="+s))}const ip=["<","&"];function Qa(t,e,n,r){return n&&n.type==="element"&&(n.tagName==="script"||n.tagName==="style")?t.value:qt(t.value,Object.assign({},r.settings.characterReferences,{subset:ip}))}function op(t,e,n,r){return r.settings.allowDangerousHtml?t.value:Qa(t,e,n,r)}function ap(t,e,n,r){return r.all(t)}const sp=Ed("type",{invalid:lp,unknown:up,handlers:{comment:Rd,doctype:Cd,element:tp,raw:op,root:ap,text:Qa}});function lp(t){throw new Error("Expected node, not `"+t+"`")}function up(t){const e=t;throw new Error("Cannot compile unknown node `"+e.type+"`")}const cp={},fp={},dp=[];function pp(t,e){const n=e||cp,r=n.quote||'"',i=r==='"'?"'":'"';if(r!=='"'&&r!=="'")throw new Error("Invalid quote `"+r+"`, expected `'` or `\"`");return{one:hp,all:mp,settings:{omitOptionalTags:n.omitOptionalTags||!1,allowParseErrors:n.allowParseErrors||!1,allowDangerousCharacters:n.allowDangerousCharacters||!1,quoteSmart:n.quoteSmart||!1,preferUnquoted:n.preferUnquoted||!1,tightAttributes:n.tightAttributes||!1,upperDoctype:n.upperDoctype||!1,tightDoctype:n.tightDoctype||!1,bogusComments:n.bogusComments||!1,tightCommaSeparatedLists:n.tightCommaSeparatedLists||!1,tightSelfClosing:n.tightSelfClosing||!1,collapseEmptyAttributes:n.collapseEmptyAttributes||!1,allowDangerousHtml:n.allowDangerousHtml||!1,voids:n.voids||gd,characterReferences:n.characterReferences||fp,closeSelfClosing:n.closeSelfClosing||!1,closeEmptyElements:n.closeEmptyElements||!1},schema:n.space==="svg"?Ya:Ad,quote:r,alternative:i}.one(Array.isArray(t)?{type:"root",children:t}:t,void 0,void 0)}function hp(t,e,n){return sp(t,e,n,this)}function mp(t){const e=[],n=t&&t.children||dp;let r=-1;for(;++ri?0:i+e:e=e>i?i:e,n=n>0?n:0,r.length<1e4)a=Array.from(r),a.unshift(e,n),t.splice(...a);else for(n&&t.splice(e,n);o0?(ct(t,t.length,0,e),t):e}const ko={}.hasOwnProperty;function bp(t){const e={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Wt(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ut=It(/[A-Za-z]/),et=It(/[\dA-Za-z]/),kp=It(/[#-'*+\--9=?A-Z^-~]/);function $r(t){return t!==null&&(t<32||t===127)}const qr=It(/\d/),_p=It(/[\dA-Fa-f]/),Ap=It(/[!-/:-@[-`{-~]/);function se(t){return t!==null&&t<-2}function Ye(t){return t!==null&&(t<0||t===32)}function Ae(t){return t===-2||t===-1||t===32}const Ep=It(new RegExp("\\p{P}|\\p{S}","u")),Mp=It(/\s/);function It(t){return e;function e(n){return n!==null&&n>-1&&t.test(String.fromCharCode(n))}}function Jt(t){const e=[];let n=-1,r=0,i=0;for(;++n55295&&o<57344){const s=t.charCodeAt(n+1);o<56320&&s>56319&&s<57344?(a=String.fromCharCode(o,s),i=1):a="�"}else a=String.fromCharCode(o);a&&(e.push(t.slice(r,n),encodeURIComponent(a)),r=n+i+1,a=""),i&&(n+=i,i=0)}return e.join("")+t.slice(r)}function Ce(t,e,n,r){const i=r?r-1:Number.POSITIVE_INFINITY;let o=0;return a;function a(l){return Ae(l)?(t.enter(n),s(l)):e(l)}function s(l){return Ae(l)&&o++a))return;const S=e.events.length;let y=S,g,m;for(;y--;)if(e.events[y][0]==="exit"&&e.events[y][1].type==="chunkFlow"){if(g){m=e.events[y][1].end;break}g=!0}for(T(r),h=S;hA;){const P=n[C];e.containerState=P[1],P[0].exit.call(e,t)}n.length=A}function I(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function Np(t,e,n){return Ce(t,t.attempt(this.parser.constructs.document,e,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ao(t){if(t===null||Ye(t)||Mp(t))return 1;if(Ep(t))return 2}function xi(t,e,n){const r=[];let i=-1;for(;++i1&&t[n][1].end.offset-t[n][1].start.offset>1?2:1;const f={...t[r][1].end},p={...t[n][1].start};Eo(f,-l),Eo(p,l),a={type:l>1?"strongSequence":"emphasisSequence",start:f,end:{...t[r][1].end}},s={type:l>1?"strongSequence":"emphasisSequence",start:{...t[n][1].start},end:p},o={type:l>1?"strongText":"emphasisText",start:{...t[r][1].end},end:{...t[n][1].start}},i={type:l>1?"strong":"emphasis",start:{...a.start},end:{...s.end}},t[r][1].end={...a.start},t[n][1].start={...s.end},u=[],t[r][1].end.offset-t[r][1].start.offset&&(u=rt(u,[["enter",t[r][1],e],["exit",t[r][1],e]])),u=rt(u,[["enter",i,e],["enter",a,e],["exit",a,e],["enter",o,e]]),u=rt(u,xi(e.parser.constructs.insideSpan.null,t.slice(r+1,n),e)),u=rt(u,[["exit",o,e],["enter",s,e],["exit",s,e],["exit",i,e]]),t[n][1].end.offset-t[n][1].start.offset?(c=2,u=rt(u,[["enter",t[n][1],e],["exit",t[n][1],e]])):c=0,ct(t,r-1,n-r+3,u),n=r+u.length-c-2;break}}for(n=-1;++n0&&Ae(h)?Ce(t,I,"linePrefix",o+1)(h):I(h)}function I(h){return h===null||se(h)?t.check(Mo,x,C)(h):(t.enter("codeFlowValue"),A(h))}function A(h){return h===null||se(h)?(t.exit("codeFlowValue"),I(h)):(t.consume(h),A)}function C(h){return t.exit("codeFenced"),e(h)}function P(h,S,y){let g=0;return m;function m(D){return h.enter("lineEnding"),h.consume(D),h.exit("lineEnding"),k}function k(D){return h.enter("codeFencedFence"),Ae(D)?Ce(h,E,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):E(D)}function E(D){return D===s?(h.enter("codeFencedFenceSequence"),O(D)):y(D)}function O(D){return D===s?(g++,h.consume(D),O):g>=a?(h.exit("codeFencedFenceSequence"),Ae(D)?Ce(h,F,"whitespace")(D):F(D)):y(D)}function F(D){return D===null||se(D)?(h.exit("codeFencedFence"),S(D)):y(D)}}}function Gp(t,e,n){const r=this;return i;function i(a){return a===null?n(a):(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),o)}function o(a){return r.parser.lazy[r.now().line]?n(a):e(a)}}const Tr={name:"codeIndented",tokenize:qp},$p={partial:!0,tokenize:Yp};function qp(t,e,n){const r=this;return i;function i(u){return t.enter("codeIndented"),Ce(t,o,"linePrefix",5)(u)}function o(u){const c=r.events[r.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?a(u):n(u)}function a(u){return u===null?l(u):se(u)?t.attempt($p,a,l)(u):(t.enter("codeFlowValue"),s(u))}function s(u){return u===null||se(u)?(t.exit("codeFlowValue"),a(u)):(t.consume(u),s)}function l(u){return t.exit("codeIndented"),e(u)}}function Yp(t,e,n){const r=this;return i;function i(a){return r.parser.lazy[r.now().line]?n(a):se(a)?(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),i):Ce(t,o,"linePrefix",5)(a)}function o(a){const s=r.events[r.events.length-1];return s&&s[1].type==="linePrefix"&&s[2].sliceSerialize(s[1],!0).length>=4?e(a):se(a)?i(a):n(a)}}const Kp={name:"codeText",previous:Xp,resolve:Wp,tokenize:Qp};function Wp(t){let e=t.length-4,n=3,r,i;if((t[n][1].type==="lineEnding"||t[n][1].type==="space")&&(t[e][1].type==="lineEnding"||t[e][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length)return this.right.slice(this.right.length-r+this.left.length,this.right.length-e+this.left.length).reverse();const i=this.left.slice(e);return i.push(...this.right.slice(this.right.length-r+this.left.length).reverse()),i}splice(e,n,r){const i=n||0;this.setCursor(Math.trunc(e));const o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return r&&sn(this.left,r),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),sn(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),sn(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e=4?e(a):t.interrupt(r.parser.constructs.flow,n,e)(a)}}function is(t,e,n,r,i,o,a,s,l){const u=l||Number.POSITIVE_INFINITY;let c=0;return f;function f(T){return T===60?(t.enter(r),t.enter(i),t.enter(o),t.consume(T),t.exit(o),p):T===null||T===32||T===41||$r(T)?n(T):(t.enter(r),t.enter(a),t.enter(s),t.enter("chunkString",{contentType:"string"}),x(T))}function p(T){return T===62?(t.enter(o),t.consume(T),t.exit(o),t.exit(i),t.exit(r),e):(t.enter(s),t.enter("chunkString",{contentType:"string"}),d(T))}function d(T){return T===62?(t.exit("chunkString"),t.exit(s),p(T)):T===null||T===60||se(T)?n(T):(t.consume(T),T===92?b:d)}function b(T){return T===60||T===62||T===92?(t.consume(T),d):d(T)}function x(T){return!c&&(T===null||T===41||Ye(T))?(t.exit("chunkString"),t.exit(s),t.exit(a),t.exit(r),e(T)):c999||d===null||d===91||d===93&&!l||d===94&&!s&&"_hiddenFootnoteSupport"in a.parser.constructs?n(d):d===93?(t.exit(o),t.enter(i),t.consume(d),t.exit(i),t.exit(r),e):se(d)?(t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),c):(t.enter("chunkString",{contentType:"string"}),f(d))}function f(d){return d===null||d===91||d===93||se(d)||s++>999?(t.exit("chunkString"),c(d)):(t.consume(d),l||(l=!Ae(d)),d===92?p:f)}function p(d){return d===91||d===92||d===93?(t.consume(d),s++,f):f(d)}}function as(t,e,n,r,i,o){let a;return s;function s(p){return p===34||p===39||p===40?(t.enter(r),t.enter(i),t.consume(p),t.exit(i),a=p===40?41:p,l):n(p)}function l(p){return p===a?(t.enter(i),t.consume(p),t.exit(i),t.exit(r),e):(t.enter(o),u(p))}function u(p){return p===a?(t.exit(o),l(a)):p===null?n(p):se(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),Ce(t,u,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),c(p))}function c(p){return p===a||p===null||se(p)?(t.exit("chunkString"),u(p)):(t.consume(p),p===92?f:c)}function f(p){return p===a||p===92?(t.consume(p),c):c(p)}}function fn(t,e){let n;return r;function r(i){return se(i)?(t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),n=!0,r):Ae(i)?Ce(t,r,n?"linePrefix":"lineSuffix")(i):e(i)}}const oh={name:"definition",tokenize:sh},ah={partial:!0,tokenize:lh};function sh(t,e,n){const r=this;let i;return o;function o(d){return t.enter("definition"),a(d)}function a(d){return os.call(r,t,s,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(d)}function s(d){return i=Wt(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),d===58?(t.enter("definitionMarker"),t.consume(d),t.exit("definitionMarker"),l):n(d)}function l(d){return Ye(d)?fn(t,u)(d):u(d)}function u(d){return is(t,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(d)}function c(d){return t.attempt(ah,f,f)(d)}function f(d){return Ae(d)?Ce(t,p,"whitespace")(d):p(d)}function p(d){return d===null||se(d)?(t.exit("definition"),r.parser.defined.push(i),e(d)):n(d)}}function lh(t,e,n){return r;function r(s){return Ye(s)?fn(t,i)(s):n(s)}function i(s){return as(t,o,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(s)}function o(s){return Ae(s)?Ce(t,a,"whitespace")(s):a(s)}function a(s){return s===null||se(s)?e(s):n(s)}}const uh={name:"hardBreakEscape",tokenize:ch};function ch(t,e,n){return r;function r(o){return t.enter("hardBreakEscape"),t.consume(o),i}function i(o){return se(o)?(t.exit("hardBreakEscape"),e(o)):n(o)}}const fh={name:"headingAtx",resolve:dh,tokenize:ph};function dh(t,e){let n=t.length-2,r=3,i,o;return t[r][1].type==="whitespace"&&(r+=2),n-2>r&&t[n][1].type==="whitespace"&&(n-=2),t[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&t[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(i={type:"atxHeadingText",start:t[r][1].start,end:t[n][1].end},o={type:"chunkText",start:t[r][1].start,end:t[n][1].end,contentType:"text"},ct(t,r,n-r+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),t}function ph(t,e,n){let r=0;return i;function i(c){return t.enter("atxHeading"),o(c)}function o(c){return t.enter("atxHeadingSequence"),a(c)}function a(c){return c===35&&r++<6?(t.consume(c),a):c===null||Ye(c)?(t.exit("atxHeadingSequence"),s(c)):n(c)}function s(c){return c===35?(t.enter("atxHeadingSequence"),l(c)):c===null||se(c)?(t.exit("atxHeading"),e(c)):Ae(c)?Ce(t,s,"whitespace")(c):(t.enter("atxHeadingText"),u(c))}function l(c){return c===35?(t.consume(c),l):(t.exit("atxHeadingSequence"),s(c))}function u(c){return c===null||c===35||Ye(c)?(t.exit("atxHeadingText"),s(c)):(t.consume(c),u)}}const hh=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Io=["pre","script","style","textarea"],mh={concrete:!0,name:"htmlFlow",resolveTo:xh,tokenize:vh},gh={partial:!0,tokenize:wh},yh={partial:!0,tokenize:bh};function xh(t){let e=t.length;for(;e--&&!(t[e][0]==="enter"&&t[e][1].type==="htmlFlow"););return e>1&&t[e-2][1].type==="linePrefix"&&(t[e][1].start=t[e-2][1].start,t[e+1][1].start=t[e-2][1].start,t.splice(e-2,2)),t}function vh(t,e,n){const r=this;let i,o,a,s,l;return u;function u(R){return c(R)}function c(R){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(R),f}function f(R){return R===33?(t.consume(R),p):R===47?(t.consume(R),o=!0,x):R===63?(t.consume(R),i=3,r.interrupt?e:_):ut(R)?(t.consume(R),a=String.fromCharCode(R),v):n(R)}function p(R){return R===45?(t.consume(R),i=2,d):R===91?(t.consume(R),i=5,s=0,b):ut(R)?(t.consume(R),i=4,r.interrupt?e:_):n(R)}function d(R){return R===45?(t.consume(R),r.interrupt?e:_):n(R)}function b(R){const pe="CDATA[";return R===pe.charCodeAt(s++)?(t.consume(R),s===pe.length?r.interrupt?e:E:b):n(R)}function x(R){return ut(R)?(t.consume(R),a=String.fromCharCode(R),v):n(R)}function v(R){if(R===null||R===47||R===62||Ye(R)){const pe=R===47,ye=a.toLowerCase();return!pe&&!o&&Io.includes(ye)?(i=1,r.interrupt?e(R):E(R)):hh.includes(a.toLowerCase())?(i=6,pe?(t.consume(R),T):r.interrupt?e(R):E(R)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(R):o?I(R):A(R))}return R===45||et(R)?(t.consume(R),a+=String.fromCharCode(R),v):n(R)}function T(R){return R===62?(t.consume(R),r.interrupt?e:E):n(R)}function I(R){return Ae(R)?(t.consume(R),I):m(R)}function A(R){return R===47?(t.consume(R),m):R===58||R===95||ut(R)?(t.consume(R),C):Ae(R)?(t.consume(R),A):m(R)}function C(R){return R===45||R===46||R===58||R===95||et(R)?(t.consume(R),C):P(R)}function P(R){return R===61?(t.consume(R),h):Ae(R)?(t.consume(R),P):A(R)}function h(R){return R===null||R===60||R===61||R===62||R===96?n(R):R===34||R===39?(t.consume(R),l=R,S):Ae(R)?(t.consume(R),h):y(R)}function S(R){return R===l?(t.consume(R),l=null,g):R===null||se(R)?n(R):(t.consume(R),S)}function y(R){return R===null||R===34||R===39||R===47||R===60||R===61||R===62||R===96||Ye(R)?P(R):(t.consume(R),y)}function g(R){return R===47||R===62||Ae(R)?A(R):n(R)}function m(R){return R===62?(t.consume(R),k):n(R)}function k(R){return R===null||se(R)?E(R):Ae(R)?(t.consume(R),k):n(R)}function E(R){return R===45&&i===2?(t.consume(R),B):R===60&&i===1?(t.consume(R),X):R===62&&i===4?(t.consume(R),te):R===63&&i===3?(t.consume(R),_):R===93&&i===5?(t.consume(R),Q):se(R)&&(i===6||i===7)?(t.exit("htmlFlowData"),t.check(gh,ce,O)(R)):R===null||se(R)?(t.exit("htmlFlowData"),O(R)):(t.consume(R),E)}function O(R){return t.check(yh,F,ce)(R)}function F(R){return t.enter("lineEnding"),t.consume(R),t.exit("lineEnding"),D}function D(R){return R===null||se(R)?O(R):(t.enter("htmlFlowData"),E(R))}function B(R){return R===45?(t.consume(R),_):E(R)}function X(R){return R===47?(t.consume(R),a="",Z):E(R)}function Z(R){if(R===62){const pe=a.toLowerCase();return Io.includes(pe)?(t.consume(R),te):E(R)}return ut(R)&&a.length<8?(t.consume(R),a+=String.fromCharCode(R),Z):E(R)}function Q(R){return R===93?(t.consume(R),_):E(R)}function _(R){return R===62?(t.consume(R),te):R===45&&i===2?(t.consume(R),_):E(R)}function te(R){return R===null||se(R)?(t.exit("htmlFlowData"),ce(R)):(t.consume(R),te)}function ce(R){return t.exit("htmlFlow"),e(R)}}function bh(t,e,n){const r=this;return i;function i(a){return se(a)?(t.enter("lineEnding"),t.consume(a),t.exit("lineEnding"),o):n(a)}function o(a){return r.parser.lazy[r.now().line]?n(a):e(a)}}function wh(t,e,n){return r;function r(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),t.attempt(Qn,e,n)}}const Th={name:"htmlText",tokenize:kh};function kh(t,e,n){const r=this;let i,o,a;return s;function s(_){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(_),l}function l(_){return _===33?(t.consume(_),u):_===47?(t.consume(_),P):_===63?(t.consume(_),A):ut(_)?(t.consume(_),y):n(_)}function u(_){return _===45?(t.consume(_),c):_===91?(t.consume(_),o=0,b):ut(_)?(t.consume(_),I):n(_)}function c(_){return _===45?(t.consume(_),d):n(_)}function f(_){return _===null?n(_):_===45?(t.consume(_),p):se(_)?(a=f,X(_)):(t.consume(_),f)}function p(_){return _===45?(t.consume(_),d):f(_)}function d(_){return _===62?B(_):_===45?p(_):f(_)}function b(_){const te="CDATA[";return _===te.charCodeAt(o++)?(t.consume(_),o===te.length?x:b):n(_)}function x(_){return _===null?n(_):_===93?(t.consume(_),v):se(_)?(a=x,X(_)):(t.consume(_),x)}function v(_){return _===93?(t.consume(_),T):x(_)}function T(_){return _===62?B(_):_===93?(t.consume(_),T):x(_)}function I(_){return _===null||_===62?B(_):se(_)?(a=I,X(_)):(t.consume(_),I)}function A(_){return _===null?n(_):_===63?(t.consume(_),C):se(_)?(a=A,X(_)):(t.consume(_),A)}function C(_){return _===62?B(_):A(_)}function P(_){return ut(_)?(t.consume(_),h):n(_)}function h(_){return _===45||et(_)?(t.consume(_),h):S(_)}function S(_){return se(_)?(a=S,X(_)):Ae(_)?(t.consume(_),S):B(_)}function y(_){return _===45||et(_)?(t.consume(_),y):_===47||_===62||Ye(_)?g(_):n(_)}function g(_){return _===47?(t.consume(_),B):_===58||_===95||ut(_)?(t.consume(_),m):se(_)?(a=g,X(_)):Ae(_)?(t.consume(_),g):B(_)}function m(_){return _===45||_===46||_===58||_===95||et(_)?(t.consume(_),m):k(_)}function k(_){return _===61?(t.consume(_),E):se(_)?(a=k,X(_)):Ae(_)?(t.consume(_),k):g(_)}function E(_){return _===null||_===60||_===61||_===62||_===96?n(_):_===34||_===39?(t.consume(_),i=_,O):se(_)?(a=E,X(_)):Ae(_)?(t.consume(_),E):(t.consume(_),F)}function O(_){return _===i?(t.consume(_),i=void 0,D):_===null?n(_):se(_)?(a=O,X(_)):(t.consume(_),O)}function F(_){return _===null||_===34||_===39||_===60||_===61||_===96?n(_):_===47||_===62||Ye(_)?g(_):(t.consume(_),F)}function D(_){return _===47||_===62||Ye(_)?g(_):n(_)}function B(_){return _===62?(t.consume(_),t.exit("htmlTextData"),t.exit("htmlText"),e):n(_)}function X(_){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(_),t.exit("lineEnding"),Z}function Z(_){return Ae(_)?Ce(t,Q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):Q(_)}function Q(_){return t.enter("htmlTextData"),a(_)}}const vi={name:"labelEnd",resolveAll:Mh,resolveTo:Sh,tokenize:Ih},_h={tokenize:Rh},Ah={tokenize:Ch},Eh={tokenize:Nh};function Mh(t){let e=-1;const n=[];for(;++e=3&&(u===null||se(u))?(t.exit("thematicBreak"),e(u)):n(u)}function l(u){return u===i?(t.consume(u),r++,l):(t.exit("thematicBreakSequence"),Ae(u)?Ce(t,s,"whitespace")(u):s(u))}}const qe={continuation:{tokenize:Vh},exit:Gh,name:"list",tokenize:jh},Bh={partial:!0,tokenize:$h},Uh={partial:!0,tokenize:Hh};function jh(t,e,n){const r=this,i=r.events[r.events.length-1];let o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,a=0;return s;function s(d){const b=r.containerState.type||(d===42||d===43||d===45?"listUnordered":"listOrdered");if(b==="listUnordered"?!r.containerState.marker||d===r.containerState.marker:qr(d)){if(r.containerState.type||(r.containerState.type=b,t.enter(b,{_container:!0})),b==="listUnordered")return t.enter("listItemPrefix"),d===42||d===45?t.check(Dn,n,u)(d):u(d);if(!r.interrupt||d===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),l(d)}return n(d)}function l(d){return qr(d)&&++a<10?(t.consume(d),l):(!r.interrupt||a<2)&&(r.containerState.marker?d===r.containerState.marker:d===41||d===46)?(t.exit("listItemValue"),u(d)):n(d)}function u(d){return t.enter("listItemMarker"),t.consume(d),t.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||d,t.check(Qn,r.interrupt?n:c,t.attempt(Bh,p,f))}function c(d){return r.containerState.initialBlankLine=!0,o++,p(d)}function f(d){return Ae(d)?(t.enter("listItemPrefixWhitespace"),t.consume(d),t.exit("listItemPrefixWhitespace"),p):n(d)}function p(d){return r.containerState.size=o+r.sliceSerialize(t.exit("listItemPrefix"),!0).length,e(d)}}function Vh(t,e,n){const r=this;return r.containerState._closeFlow=void 0,t.check(Qn,i,o);function i(s){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Ce(t,e,"listItemIndent",r.containerState.size+1)(s)}function o(s){return r.containerState.furtherBlankLines||!Ae(s)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,a(s)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,t.attempt(Uh,e,a)(s))}function a(s){return r.containerState._closeFlow=!0,r.interrupt=void 0,Ce(t,t.attempt(qe,e,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s)}}function Hh(t,e,n){const r=this;return Ce(t,i,"listItemIndent",r.containerState.size+1);function i(o){const a=r.events[r.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?e(o):n(o)}}function Gh(t){t.exit(this.containerState.type)}function $h(t,e,n){const r=this;return Ce(t,i,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){const a=r.events[r.events.length-1];return!Ae(o)&&a&&a[1].type==="listItemPrefixWhitespace"?e(o):n(o)}}const Ro={name:"setextUnderline",resolveTo:qh,tokenize:Yh};function qh(t,e){let n=t.length,r,i,o;for(;n--;)if(t[n][0]==="enter"){if(t[n][1].type==="content"){r=n;break}t[n][1].type==="paragraph"&&(i=n)}else t[n][1].type==="content"&&t.splice(n,1),!o&&t[n][1].type==="definition"&&(o=n);const a={type:"setextHeading",start:{...t[i][1].start},end:{...t[t.length-1][1].end}};return t[i][1].type="setextHeadingText",o?(t.splice(i,0,["enter",a,e]),t.splice(o+1,0,["exit",t[r][1],e]),t[r][1].end={...t[o][1].end}):t[r][1]=a,t.push(["exit",a,e]),t}function Yh(t,e,n){const r=this;let i;return o;function o(u){let c=r.events.length,f;for(;c--;)if(r.events[c][1].type!=="lineEnding"&&r.events[c][1].type!=="linePrefix"&&r.events[c][1].type!=="content"){f=r.events[c][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||f)?(t.enter("setextHeadingLine"),i=u,a(u)):n(u)}function a(u){return t.enter("setextHeadingLineSequence"),s(u)}function s(u){return u===i?(t.consume(u),s):(t.exit("setextHeadingLineSequence"),Ae(u)?Ce(t,l,"lineSuffix")(u):l(u))}function l(u){return u===null||se(u)?(t.exit("setextHeadingLine"),e(u)):n(u)}}const Kh={tokenize:Wh};function Wh(t){const e=this,n=t.attempt(Qn,r,t.attempt(this.parser.constructs.flowInitial,i,Ce(t,t.attempt(this.parser.constructs.flow,i,t.attempt(eh,i)),"linePrefix")));return n;function r(o){if(o===null){t.consume(o);return}return t.enter("lineEndingBlank"),t.consume(o),t.exit("lineEndingBlank"),e.currentConstruct=void 0,n}function i(o){if(o===null){t.consume(o);return}return t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),e.currentConstruct=void 0,n}}const Xh={resolveAll:ls()},Qh=ss("string"),Zh=ss("text");function ss(t){return{resolveAll:ls(t==="text"?Jh:void 0),tokenize:e};function e(n){const r=this,i=this.parser.constructs[t],o=n.attempt(i,a,s);return a;function a(c){return u(c)?o(c):s(c)}function s(c){if(c===null){n.consume(c);return}return n.enter("data"),n.consume(c),l}function l(c){return u(c)?(n.exit("data"),o(c)):(n.consume(c),l)}function u(c){if(c===null)return!0;const f=i[c];let p=-1;if(f)for(;++p-1){const s=a[0];typeof s=="string"?a[0]=s.slice(r):a.shift()}o>0&&a.push(t[i].slice(0,o))}return a}function dm(t,e){let n=-1;const r=[];let i;for(;++n0){const He=oe.tokenStack[oe.tokenStack.length-1];(He[1]||Po).call(oe,void 0,He[0])}for(K.position={start:kt(j.length>0?j[0][1].start:{line:1,column:1,offset:0}),end:kt(j.length>0?j[j.length-2][1].end:{line:1,column:1,offset:0})},we=-1;++we1?"-"+s:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};t.patch(e,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return t.patch(e,u),t.applyData(e,u)}function Im(t,e){const n={type:"element",tagName:"h"+e.depth,properties:{},children:t.all(e)};return t.patch(e,n),t.applyData(e,n)}function Rm(t,e){if(t.options.allowDangerousHtml){const n={type:"raw",value:e.value};return t.patch(e,n),t.applyData(e,n)}}function fs(t,e){const n=e.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(e.label||e.identifier)+"]"),e.type==="imageReference")return[{type:"text",value:"!["+e.alt+r}];const i=t.all(e),o=i[0];o&&o.type==="text"?o.value="["+o.value:i.unshift({type:"text",value:"["});const a=i[i.length-1];return a&&a.type==="text"?a.value+=r:i.push({type:"text",value:r}),i}function Cm(t,e){const n=String(e.identifier).toUpperCase(),r=t.definitionById.get(n);if(!r)return fs(t,e);const i={src:Jt(r.url||""),alt:e.alt};r.title!==null&&r.title!==void 0&&(i.title=r.title);const o={type:"element",tagName:"img",properties:i,children:[]};return t.patch(e,o),t.applyData(e,o)}function Nm(t,e){const n={src:Jt(e.url)};e.alt!==null&&e.alt!==void 0&&(n.alt=e.alt),e.title!==null&&e.title!==void 0&&(n.title=e.title);const r={type:"element",tagName:"img",properties:n,children:[]};return t.patch(e,r),t.applyData(e,r)}function Lm(t,e){const n={type:"text",value:e.value.replace(/\r?\n|\r/g," ")};t.patch(e,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return t.patch(e,r),t.applyData(e,r)}function Pm(t,e){const n=String(e.identifier).toUpperCase(),r=t.definitionById.get(n);if(!r)return fs(t,e);const i={href:Jt(r.url||"")};r.title!==null&&r.title!==void 0&&(i.title=r.title);const o={type:"element",tagName:"a",properties:i,children:t.all(e)};return t.patch(e,o),t.applyData(e,o)}function Dm(t,e){const n={href:Jt(e.url)};e.title!==null&&e.title!==void 0&&(n.title=e.title);const r={type:"element",tagName:"a",properties:n,children:t.all(e)};return t.patch(e,r),t.applyData(e,r)}function Om(t,e,n){const r=t.all(e),i=n?zm(n):ds(e),o={},a=[];if(typeof e.checked=="boolean"){const c=r[0];let f;c&&c.type==="element"&&c.tagName==="p"?f=c:(f={type:"element",tagName:"p",properties:{},children:[]},r.unshift(f)),f.children.length>0&&f.children.unshift({type:"text",value:" "}),f.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:e.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let s=-1;for(;++s1}function Fm(t,e){const n={},r=t.all(e);let i=-1;for(typeof e.start=="number"&&e.start!==1&&(n.start=e.start);++i0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Vm(t){const e=hs(t),n=ps(t);if(e&&n)return{start:e,end:n}}function Hm(t,e){const n=t.all(e),r=n.shift(),i=[];if(r){const a={type:"element",tagName:"thead",properties:{},children:t.wrap([r],!0)};t.patch(e.children[0],a),i.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:t.wrap(n,!0)},s=hs(e.children[1]),l=ps(e.children[e.children.length-1]);s&&l&&(a.position={start:s,end:l}),i.push(a)}const o={type:"element",tagName:"table",properties:{},children:t.wrap(i,!0)};return t.patch(e,o),t.applyData(e,o)}function Gm(t,e,n){const r=n?n.children:void 0,o=(r?r.indexOf(e):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,s=a?a.length:e.children.length;let l=-1;const u=[];for(;++l0,!0),r[0]),i=r.index+r[0].length,r=n.exec(e);return o.push(zo(e.slice(i),i>0,!1)),o.join("")}function zo(t,e,n){let r=0,i=t.length;if(e){let o=t.codePointAt(r);for(;o===Do||o===Oo;)r++,o=t.codePointAt(r)}if(n){let o=t.codePointAt(i-1);for(;o===Do||o===Oo;)i--,o=t.codePointAt(i-1)}return i>r?t.slice(r,i):""}function Ym(t,e){const n={type:"text",value:qm(String(e.value))};return t.patch(e,n),t.applyData(e,n)}function Km(t,e){const n={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(e,n),t.applyData(e,n)}const Wm={blockquote:km,break:_m,code:Am,delete:Em,emphasis:Mm,footnoteReference:Sm,heading:Im,html:Rm,imageReference:Cm,image:Nm,inlineCode:Lm,linkReference:Pm,link:Dm,listItem:Om,list:Fm,paragraph:Bm,root:Um,strong:jm,table:Hm,tableCell:$m,tableRow:Gm,text:Ym,thematicBreak:Km,toml:Rn,yaml:Rn,definition:Rn,footnoteDefinition:Rn};function Rn(){}const gs=-1,Zn=0,Vn=1,Hn=2,bi=3,wi=4,Ti=5,ki=6,ys=7,xs=8,Fo=typeof self=="object"?self:globalThis,Xm=(t,e)=>{const n=(i,o)=>(t.set(o,i),i),r=i=>{if(t.has(i))return t.get(i);const[o,a]=e[i];switch(o){case Zn:case gs:return n(a,i);case Vn:{const s=n([],i);for(const l of a)s.push(r(l));return s}case Hn:{const s=n({},i);for(const[l,u]of a)s[r(l)]=r(u);return s}case bi:return n(new Date(a),i);case wi:{const{source:s,flags:l}=a;return n(new RegExp(s,l),i)}case Ti:{const s=n(new Map,i);for(const[l,u]of a)s.set(r(l),r(u));return s}case ki:{const s=n(new Set,i);for(const l of a)s.add(r(l));return s}case ys:{const{name:s,message:l}=a;return n(new Fo[s](l),i)}case xs:return n(BigInt(a),i);case"BigInt":return n(Object(BigInt(a)),i)}return n(new Fo[o](a),i)};return r},Bo=t=>Xm(new Map,t)(0),Vt="",{toString:Qm}={},{keys:Zm}=Object,ln=t=>{const e=typeof t;if(e!=="object"||!t)return[Zn,e];const n=Qm.call(t).slice(8,-1);switch(n){case"Array":return[Vn,Vt];case"Object":return[Hn,Vt];case"Date":return[bi,Vt];case"RegExp":return[wi,Vt];case"Map":return[Ti,Vt];case"Set":return[ki,Vt]}return n.includes("Array")?[Vn,n]:n.includes("Error")?[ys,n]:[Hn,n]},Cn=([t,e])=>t===Zn&&(e==="function"||e==="symbol"),Jm=(t,e,n,r)=>{const i=(a,s)=>{const l=r.push(a)-1;return n.set(s,l),l},o=a=>{if(n.has(a))return n.get(a);let[s,l]=ln(a);switch(s){case Zn:{let c=a;switch(l){case"bigint":s=xs,c=a.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+l);c=null;break;case"undefined":return i([gs],a)}return i([s,c],a)}case Vn:{if(l)return i([l,[...a]],a);const c=[],f=i([s,c],a);for(const p of a)c.push(o(p));return f}case Hn:{if(l)switch(l){case"BigInt":return i([l,a.toString()],a);case"Boolean":case"Number":case"String":return i([l,a.valueOf()],a)}if(e&&"toJSON"in a)return o(a.toJSON());const c=[],f=i([s,c],a);for(const p of Zm(a))(t||!Cn(ln(a[p])))&&c.push([o(p),o(a[p])]);return f}case bi:return i([s,a.toISOString()],a);case wi:{const{source:c,flags:f}=a;return i([s,{source:c,flags:f}],a)}case Ti:{const c=[],f=i([s,c],a);for(const[p,d]of a)(t||!(Cn(ln(p))||Cn(ln(d))))&&c.push([o(p),o(d)]);return f}case ki:{const c=[],f=i([s,c],a);for(const p of a)(t||!Cn(ln(p)))&&c.push(o(p));return f}}const{message:u}=a;return i([s,{name:l,message:u}],a)};return o},Uo=(t,{json:e,lossy:n}={})=>{const r=[];return Jm(!(e||n),!!e,new Map,r)(t),r},Gn=typeof structuredClone=="function"?(t,e)=>e&&("json"in e||"lossy"in e)?Bo(Uo(t,e)):structuredClone(t):(t,e)=>Bo(Uo(t,e));function eg(t,e){const n=[{type:"text",value:"↩"}];return e>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(e)}]}),n}function tg(t,e){return"Back to reference "+(t+1)+(e>1?"-"+e:"")}function ng(t){const e=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",n=t.options.footnoteBackContent||eg,r=t.options.footnoteBackLabel||tg,i=t.options.footnoteLabel||"Footnotes",o=t.options.footnoteLabelTagName||"h2",a=t.options.footnoteLabelProperties||{className:["sr-only"]},s=[];let l=-1;for(;++l0&&b.push({type:"text",value:" "});let I=typeof n=="string"?n:n(l,d);typeof I=="string"&&(I={type:"text",value:I}),b.push({type:"element",tagName:"a",properties:{href:"#"+e+"fnref-"+p+(d>1?"-"+d:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(l,d),className:["data-footnote-backref"]},children:Array.isArray(I)?I:[I]})}const v=c[c.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const I=v.children[v.children.length-1];I&&I.type==="text"?I.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...b)}else c.push(...b);const T={type:"element",tagName:"li",properties:{id:e+"fn-"+p},children:t.wrap(c,!0)};t.patch(u,T),s.push(T)}if(s.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Gn(a),id:"footnote-label"},children:[{type:"text",value:i}]},{type:"text",value:` +`},{type:"element",tagName:"ol",properties:{},children:t.wrap(s,!0)},{type:"text",value:` +`}]}}const vs=function(t){if(t==null)return ag;if(typeof t=="function")return Jn(t);if(typeof t=="object")return Array.isArray(t)?rg(t):ig(t);if(typeof t=="string")return og(t);throw new Error("Expected function, string, or object as test")};function rg(t){const e=[];let n=-1;for(;++n":""))+")"})}return p;function p(){let d=bs,b,x,v;if((!e||o(l,u,c[c.length-1]||void 0))&&(d=fg(n(l,c)),d[0]===jo))return d;if("children"in l&&l.children){const T=l;if(T.children&&d[0]!==ug)for(x=(r?T.children.length:-1)+a,v=c.concat(T);x>-1&&x0&&n.push({type:"text",value:` `}),n}function Vo(t){let e=0,n=t.charCodeAt(e);for(;n===9||n===32;)e++,n=t.charCodeAt(e);return t.slice(e)}function Ho(t,e){const n=hg(t,e),r=n.one(t,void 0),i=ng(n),o=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&o.children.push({type:"text",value:` -`},i),o}function vg(t,e){return t&&"run"in t?async function(n,r){const i=Ho(n,{file:r,...e});await t.run(i,r)}:function(n,r){return Ho(n,{file:r,...t||e})}}function Go(t){if(t)throw t}var Ar,$o;function bg(){if($o)return Ar;$o=1;var t=Object.prototype.hasOwnProperty,e=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=function(u){return typeof Array.isArray=="function"?Array.isArray(u):e.call(u)==="[object Array]"},o=function(u){if(!u||e.call(u)!=="[object Object]")return!1;var c=t.call(u,"constructor"),f=u.constructor&&u.constructor.prototype&&t.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!c&&!f)return!1;var p;for(p in u);return typeof p>"u"||t.call(u,p)},s=function(u,c){n&&c.name==="__proto__"?n(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},a=function(u,c){if(c==="__proto__")if(t.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return Ar=function l(){var u,c,f,p,d,b,x=arguments[0],v=1,T=arguments.length,I=!1;for(typeof x=="boolean"&&(I=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});vs.length;let l;a&&s.push(i);try{l=t.apply(this,s)}catch(u){const c=u;if(a&&n)throw c;return i(c)}a||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(s,...a){n||(n=!0,e(s,...a))}function o(s){i(null,s)}}class We extends Error{constructor(e,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",o={},s=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof e=="string"?i=e:!o.cause&&e&&(s=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?o.ruleId=r:(o.source=r.slice(0,l),o.ruleId=r.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){const l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}const a=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file,this.message=i,this.line=a?a.line:void 0,this.name=dn(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=s&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual,this.expected,this.note,this.url}}We.prototype.file="";We.prototype.name="";We.prototype.reason="";We.prototype.message="";We.prototype.stack="";We.prototype.column=void 0;We.prototype.line=void 0;We.prototype.ancestors=void 0;We.prototype.cause=void 0;We.prototype.fatal=void 0;We.prototype.place=void 0;We.prototype.ruleId=void 0;We.prototype.source=void 0;const lt={basename:Ag,dirname:_g,extname:Eg,join:Mg,sep:"/"};function Ag(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');wn(t);let n=0,r=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else r<0&&(o=!0,r=i+1);return r<0?"":t.slice(n,r)}if(e===t)return"";let s=-1,a=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else s<0&&(o=!0,s=i+1),a>-1&&(t.codePointAt(i)===e.codePointAt(a--)?a<0&&(r=i):(a=-1,r=s));return n===r?r=s:r<0&&(r=t.length),t.slice(n,r)}function _g(t){if(wn(t),t.length===0)return".";let e=-1,n=t.length,r;for(;--n;)if(t.codePointAt(n)===47){if(r){e=n;break}}else r||(r=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function Eg(t){wn(t);let e=t.length,n=-1,r=0,i=-1,o=0,s;for(;e--;){const a=t.codePointAt(e);if(a===47){if(s){r=e+1;break}continue}n<0&&(s=!0,n=e+1),a===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||n<0||o===0||o===1&&i===n-1&&i===r+1?"":t.slice(i,n)}function Mg(...t){let e=-1,n;for(;++e0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function Ig(t,e){let n="",r=0,i=-1,o=0,s=-1,a,l;for(;++s<=t.length;){if(s2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),i=s,o=0;continue}}else if(n.length>0){n="",r=0,i=s,o=0;continue}}e&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+t.slice(i+1,s):n=t.slice(i+1,s),r=s-i-1;i=s,o=0}else a===46&&o>-1?o++:o=-1}return n}function wn(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const Rg={cwd:Cg};function Cg(){return"/"}function Qr(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function Ng(t){if(typeof t=="string")t=new URL(t);else if(!Qr(t)){const e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){const e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return Lg(t)}function Lg(t){if(t.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const e=t.pathname;let n=-1;for(;++n0){let[d,...b]=c;const x=r[p][1];Xr(x)&&Xr(d)&&(d=_r(!0,x,d)),r[p]=[u,d,...b]}}}}const zg=new Ai().freeze();function Ir(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Rr(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Cr(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function qo(t){if(!Xr(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Ko(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function Nn(t){return Bg(t)?t:new Pg(t)}function Bg(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function Ug(t){return typeof t=="string"||jg(t)}function jg(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}function _i(){const t=zg().use(Tm).use(vg).use(gp);return{process:e=>t.processSync(e).toString()}}const Vg={relative:""},Hg={"h-full":"","w-full":""},Gg={key:0,class:"animate-stripe",absolute:"",left:"1/2",bottom:"20%",z:"20","rounded-2xl":"",text:"primary-600","px-2":"","py-2":"",transform:"translate-x--1/2"},$g={bg:"primary-50","rounded-xl":"","px-10":"","py-6":""},Yg=["innerHTML"],qg=Fe({__name:"Stage",props:{paused:{type:Boolean,default:!1}},setup(t){const e=W(),n=W(),{stageView:r}=Ze(Xt()),{mouthOpenSize:i}=Ze(iu()),{audioContext:o,calculateVolume:s}=gs(),{onBeforeMessageComposed:a,onBeforeSend:l,onTokenLiteral:u,onTokenSpecial:c,onStreamEnd:f,streamingMessage:p,onAssistantResponseEnd:d}=St(),{process:b}=_i(),x=ui(),v=W(),T=W(!1),I=W(!1),_=or({handlers:[A=>new Promise(te=>{const ce=o.createBufferSource();ce.buffer=A.data.audioBuffer,ce.connect(o.destination),ce.connect(v.value),T.value=!0,ce.start(0),ce.onended=()=>{T.value=!1,te()}})]}),C=Bl(),{ssmlEnabled:P,activeSpeechProvider:h,activeSpeechModel:M,activeSpeechVoice:y,pitch:g}=Ze(C);async function m(A){try{if(!h.value){console.warn("No active speech provider configured");return}if(!y.value){console.warn("No active speech voice configured");return}const te=x.getProviderInstance(h.value);if(!te){console.error("Failed to initialize speech provider");return}const ce=x.getProviderConfig(h.value),R=P.value?C.generateSSML(A.data,y.value,{...ce,pitch:g.value}):A.data,pe=await Ul({...te.speech(M.value,ce),input:R,voice:y.value.id}),ye=await o.decodeAudioData(pe);await _.add({audioBuffer:ye,text:A.data})}catch(te){console.error("Speech generation failed:",te)}}const k=or({handlers:[m]});k.on("add",A=>{console.debug("ttsQueue added",A)});const E=jl(k),{live2dCurrentMotion:O}=Ze(Xt()),z=or({handlers:[async A=>{if(r.value==="3d"){const te=Pa[A.data];if(!te)return;await n.value.setExpression(te)}else r.value==="2d"&&(O.value={group:Da[A.data]})}]}),D=Vl(z);D.onHandlerEvent("emotion",A=>{console.debug("emotion detected",A)});const B=Hl();B.onHandlerEvent("delay",A=>{console.debug("delay detected",A)});function X(){requestAnimationFrame(X),T.value&&(i.value=s(v.value,"linear"))}function Z(){I.value||(X(),o.resume(),I.value=!0)}function Q(){v.value||(v.value=o.createAnalyser())}return a(async()=>{Q(),Z()}),l(async()=>{O.value={group:Si}}),u(async A=>{await E.add(A)}),c(async A=>{await B.add(A),await D.add(A)}),f(async()=>{await B.add(Gl)}),d(async A=>{}),Ft(()=>{var te,ce,R;I.value=!1;const A=window;(te=A.electron)==null||te.ipcRenderer.removeAllListeners("before-hide"),(ce=A.electron)==null||ce.ipcRenderer.removeAllListeners("after-show"),(R=A.electron)==null||R.ipcRenderer.removeAllListeners("before-quit")}),pn(()=>{var te,ce,R;const A=window;(te=A.electron)==null||te.ipcRenderer.on("before-hide",()=>{O.value={group:Ra}}),(ce=A.electron)==null||ce.ipcRenderer.on("after-show",()=>{O.value={group:Ca}}),(R=A.electron)==null||R.ipcRenderer.on("before-quit",()=>{O.value={group:Si}})}),pn(async()=>{e.value=Na("duckdb-wasm://?bundles=import-url"),await e.value.execute(La`CREATE TABLE memory_test (vec FLOAT[768]);`)}),(A,te)=>(ee(),ie("div",Vg,[F("div",Hg,[H(r)==="2d"?(ee(),Qt(wu,{key:0,"mouth-open-size":H(i),"min-w":"50% (ee(),ie("header",Jg,[F("div",ey,[ke(Jl)]),ke(H(Cl),{class:"m-1 block max-h-[10lh] min-h-[1lh] rounded-lg bg-zinc-100 p-2 text-lg text-zinc-500 outline-none dark:bg-zinc-800 dark:text-zinc-400",to:"/settings"},{default:Be(()=>n[0]||(n[0]=[F("div",{"i-solar:settings-minimalistic-bold-duotone":""},null,-1)])),_:1})]))}});function wa(t,e){const n=fs(e??{},{...Fi.getDefaultRealTimeVADOptions("v5"),preSpeechPadFrames:30,positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,minSpeechFrames:30,auto:!0}),r=W(),i=Nl("microphone");async function o(){if(r.value&&(r.value.destroy(),r.value=void 0,console.warn("existing MicVAD destroyed")),!i.value)return;const s=H(t);if(!s)return;const a=await navigator.mediaDevices.getUserMedia({audio:{deviceId:s}});r.value=await Fi.MicVAD.new({...n,stream:a}),n.auto&&r.value.start()}return je(i,o,{immediate:!0}),je(Ll(t),o,{immediate:!0}),Pl(o),Ft(()=>{r.value&&(r.value.destroy(),r.value=void 0)}),{destroy:()=>{r.value&&(r.value.destroy(),r.value=void 0)},start:()=>{r.value&&r.value.start()}}}function ny(t,e){const n=fs(e,{onLoading:()=>{},onInitiate:()=>{},onProgress:()=>{},onDone:()=>{},onReady:()=>{},onStart:()=>{},onUpdate:()=>{},onComplete:()=>{}}),{post:r,data:i,terminate:o}=Dl(t,{type:"module"}),s=W(null),a=W(""),l=W([]),u=W(!1),c=W(0),f=W("");return je(i,p=>{var d,b,x,v,T,I,_,C;switch(p.status){case"loading":s.value="loading",a.value=p.data,(d=n.onLoading)==null||d.call(n,p.data);break;case"initiate":l.value.push(p),(b=n.onInitiate)==null||b.call(n,p);break;case"progress":l.value=l.value.map(P=>P.file===p.file?{...P,...p}:P),(x=n.onProgress)==null||x.call(n,p);break;case"done":l.value=l.value.filter(P=>P.file!==p.file),(v=n.onDone)==null||v.call(n,p);break;case"ready":s.value="ready",(T=n.onReady)==null||T.call(n);break;case"start":u.value=!0,(I=n.onStart)==null||I.call(n);break;case"update":c.value=p.tps,(_=n.onUpdate)==null||_.call(n,p.tps);break;case"complete":u.value=!1,f.value=p.output[0]||"",console.debug("Whisper result:",f.value),(C=n.onComplete)==null||C.call(n,p.output[0]);break}}),Ft(()=>{o()}),{transcribe:p=>r(p),status:s,loadingMessage:a,loadingProgress:l,transcribing:u,tps:c,result:f,load:()=>r({type:"load"}),terminate:o}}const ry="/assets/worker-KF4IHpL4.js";async function iy(t,e){const n=new ArrayBuffer(44+t.length*2),r=new DataView(n);Ln(r,0,"RIFF"),r.setUint32(4,36+t.length*2,!0),Ln(r,8,"WAVE"),Ln(r,12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,e,!0),r.setUint32(28,e*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),Ln(r,36,"data"),r.setUint32(40,t.length*2,!0),oy(r,44,t);const i=new Blob([r],{type:"audio/wav"});return new Promise((o,s)=>{const a=new FileReader;a.onload=()=>{const l=a.result.split(",")[1];o(l)},a.onerror=s,a.readAsDataURL(i)})}function Ln(t,e,n){for(let r=0;r{jn().then(()=>{i.update(),o.value=i.height.value})}),u(async()=>{jn().then(()=>{i.update(),o.value=i.height.value})}),(c,f)=>{const p=ps("auto-animate");return ee(),ie("div",sy,[f[2]||(f[2]=F("div",{"flex-1":""},null,-1)),_t((ee(),ie("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"",flex:"~ col","overflow-scroll":""},[f[1]||(f[1]=F("div",{"flex-1":""},null,-1)),(ee(!0),ie(ai,null,li(H(n),(d,b)=>(ee(),ie("div",{key:b,"mb-2":""},[d.role==="error"?(ee(),ie("div",ay,[F("div",ly,[F("div",uy,[F("div",cy,[F("span",fy,ge(H(s)("stage.chat.message.character-name.core-system")),1)]),f[0]||(f[0]=F("div",{"i-solar:danger-triangle-bold-duotone":"","text-violet-500":""},null,-1))]),H(r)?(ee(),ie("div",dy)):(ee(),ie("div",{key:1,class:"markdown-content break-words text-violet-500",text:"base {if(!E||!E.trim())return;const O=o.getProviderConfig(s.value);await d(E,{chatProvider:o.getProviderInstance(s.value),model:a.value,providerConfig:O})}});async function h(){if(e.value.trim())try{const E=o.getProviderConfig(s.value);await d(e.value,{chatProvider:o.getProviderInstance(s.value),model:a.value,providerConfig:E})}catch(E){x.value.pop(),x.value.push({role:"error",content:E.message})}}const{destroy:M,start:y}=wa(p,{onSpeechStart:()=>{n.value=!0},onVADMisfire:()=>{n.value=!1},onSpeechEnd:E=>{n.value=!1,m(E)},auto:!1});function g(){C.value!=="loading"&&(_(),y())}async function m(E){await v.resume();const O=await iy(E,v.sampleRate);I({type:"generate",data:{audio:O,language:"en"}})}async function k(E){const O=E.target,z=u.value.find(D=>D.deviceId===O.value);if(!z){c.value=void 0;return}c.value=z}return je(f,async E=>{E==="false"&&(M(),P())}),b(async()=>{e.value=""}),(E,O)=>(ee(),ie("div",_y,[F("fieldset",Ey,[F("label",{class:at([r.value==="chat"?"bg-primary-100 dark:bg-primary-900":"bg-white dark:bg-primary-950",r.value==="chat"?"text-primary-500 dark:text-primary-500":"",{"transition-colors-none ":H(l)}]),flex:"~ row",checked:r.value==="chat","aria-checked":r.value==="chat",border:"solid l-2 t-2 b-2 primary-100 dark:primary-900",bg:"hover:primary-100 dark:hover:primary-900",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500",transition:"all duration-250 ease-in-out","cursor-pointer":"","items-center":"","gap-1":"","rounded-l-lg":"","px-2":""},[_t(F("input",{"onUpdate:modelValue":O[0]||(O[0]=z=>r.value=z),type:"radio",name:"tab",value:"chat",hidden:""},null,512),[[ir,r.value]]),O[5]||(O[5]=F("div",{"i-solar:dialog-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),F("div",Sy,[F("span",Iy,ge(H(T)("stage.chat.tabs.chat")),1)])],10,My),F("label",{class:at([r.value==="custom"?"bg-primary-100 dark:bg-primary-900":"bg-white dark:bg-primary-950",r.value==="custom"?"text-primary-500 dark:text-primary-500":"",{"transition-colors-none ":H(l)}]),flex:"~ row",checked:r.value==="custom","aria-checked":r.value==="custom",border:"solid t-2 b-2 primary-100 dark:primary-900",bg:"hover:primary-100 dark:hover:primary-900",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500",transition:"all duration-250 ease-in-out","cursor-pointer":"","items-center":"","gap-1":"","px-2":""},[_t(F("input",{"onUpdate:modelValue":O[1]||(O[1]=z=>r.value=z),type:"radio",name:"tab",value:"custom",hidden:""},null,512),[[ir,r.value]]),O[6]||(O[6]=F("div",{"i-solar:star-fall-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),F("div",Cy,[F("span",null,ge(H(T)("stage.chat.tabs.custom")),1)])],10,Ry),F("label",{class:at([r.value==="clothes"?"bg-primary-100 dark:bg-primary-900":"bg-white dark:bg-primary-950",r.value==="clothes"?"text-primary-500 dark:text-primary-500":"",{"transition-colors-none ":H(l)}]),flex:"~ row",checked:r.value==="clothes","aria-checked":r.value==="clothes",border:"solid r-2 t-2 b-2 primary-100 dark:primary-900",bg:"hover:primary-100 dark:hover:primary-900",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500",transition:"all duration-250 ease-in-out","cursor-pointer":"","items-center":"","gap-1":"","rounded-r-lg":"","px-2":""},[_t(F("input",{"onUpdate:modelValue":O[2]||(O[2]=z=>r.value=z),type:"radio",name:"tab",value:"clothes",hidden:""},null,512),[[ir,r.value]]),O[7]||(O[7]=F("div",{"i-solar:magic-stick-3-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),F("div",Ly,[F("span",null,ge(H(T)("stage.chat.tabs.clothes")),1)])],10,Ny)]),F("div",Py,[F("div",Dy,[ke(Ay,{"h-full":"","flex-1":"","p-4":"",w:"full","max-h":"e.value=z),placeholder:H(T)("stage.message"),text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500 placeholder:primary-300 placeholder:hover:primary-500 placeholder:dark:primary-300/50 placeholder:dark:hover:primary-500",bg:"primary-100 dark:primary-400/20","min-h":"[100px]","max-h":"[300px]","w-full":"","rounded-t-xl":"","p-4":"","font-medium":"","outline-none":"",transition:"all duration-250 ease-in-out placeholder:all placeholder:duration-250 placeholder:ease-in-out",class:at({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:h},null,8,["modelValue","placeholder","class"])])])]),F("div",Fy,[F("button",{bg:"complementary-100 hover:complementary-200 dark:complementary-800 dark:hover:complementary-700",transition:"all duration-250 ease-in-out",class:at({"transition-colors-none":H(l)}),text:"complementary-400","mb-6":"",flex:"","cursor-pointer":"","items-center":"","justify-center":"","gap-2":"","rounded-full":"","px-4":"","py-2":"",onClick:g},[ke(Fl,{mode:"out-in"},{default:Be(()=>[H(C)===null?(ee(),ie("div",zy,ge(H(T)("stage.operations.load-models")),1)):H(C)==="loading"?(ee(),ie("div",By,[O[8]||(O[8]=F("div",{"i-svg-spinners:bouncing-ball":"",class:"text-cyan"},null,-1)),F("span",null,ge(H(T)("stage.operations.load-models-status.loading")),1)])):H(C)==="ready"?(ee(),ie("div",Uy,[O[9]||(O[9]=F("div",{"i-lucide:check":"",class:"text-cyan"},null,-1)),F("span",null,ge(H(T)("stage.operations.load-models-status.ready")),1)])):it("",!0)]),_:1})],2),F("div",jy,[ke(H(ci),null,{default:Be(()=>[i.value?(ee(),ie("fieldset",Vy,[(ee(!0),ie(ai,null,li(H(u),(z,D)=>(ee(),ie("label",{key:D,class:"[&_div_span]:dark:hover:bg-cyan-300 [&_div_span]:dark:hover:bg-cyan-900"},[F("input",{type:"radio",name:"audioInput",value:z.deviceId,hidden:"",onChange:k},null,40,Hy),F("div",Gy,[F("div",$y,[z.deviceId===H(p)?(ee(),ie("div",Yy)):it("",!0)]),F("span",{"inline-block":"",class:at([z.deviceId===H(p)?"cyan-400 dark:text-white":"cyan-400/50 dark:text-white/50"]),transition:"all duration-250 ease-in-out"},ge(z.label),3)])]))),128))])):it("",!0)]),_:1}),F("label",{bg:"complementary-100 hover:complementary-200 dark:complementary-800 dark:hover:complementary-700",transition:"all duration-250 ease-in-out",class:at({"transition-colors-none":H(l)}),text:"complementary-400","mb-6":"",flex:"","cursor-pointer":"","items-center":"","justify-center":"","gap-2":"","rounded-full":"","px-4":"","py-2":""},[_t(F("input",{"onUpdate:modelValue":O[4]||(O[4]=z=>i.value=z),type:"checkbox",hidden:""},null,512),[[Jr,i.value]]),O[10]||(O[10]=F("div",{"i-solar:microphone-2-bold-duotone":""},null,-1)),F("div",null,[n.value?(ee(),ie("span",Ky,"Listening...")):(ee(),ie("span",qy,ge(H(T)("settings.microphone")),1))])],2)])])]))}}),Xy=Kn(Wy,[["__scopeId","data-v-0b41b5bf"]]),Qy={py:"1",flex:"~ col",rounded:"lg","overflow-hidden":""},Zy={key:0,flex:"",mr:"12"},Jy={flex:"~ col",border:"4 solid primary-200/50 dark:primary-500/50",shadow:"md primary-200/50 dark:none","min-w-20":"","rounded-lg":"","px-2":"","py-1":"",h:"unset {jn().then(()=>{i.update(),o.value=i.height.value})}),l(async()=>{jn().then(()=>{i.update(),o.value=i.height.value})}),(u,c)=>{const f=ps("auto-animate");return ee(),ie("div",Qy,[c[1]||(c[1]=F("div",{"flex-1":""},null,-1)),_t((ee(),ie("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"","max-h":"30vh",flex:"~ col","overflow-scroll":""},[c[0]||(c[0]=F("div",{"flex-1":""},null,-1)),(ee(!0),ie(ai,null,li(H(r),(p,d)=>(ee(),ie("div",{key:d,"mb-2":""},[p.role==="assistant"?(ee(),ie("div",Zy,[F("div",Jy,[F("div",null,[F("span",e0,ge(H(n)("stage.chat.message.character-name.airi")),1)]),p.content?(ee(),ie("div",{key:0,class:"markdown-content",text:"base {n.value=!0},onVADMisfire:()=>{n.value=!1},onSpeechEnd:v=>{n.value=!1,x()},auto:!1});function x(v){alert("Transcription is not implemented yet")}return je(s,async v=>{v==="false"&&d()}),c(async()=>{e.value=""}),pn(()=>{b()}),(v,T)=>(ee(),ie("div",null,[F("div",u0,[ke(l0,{absolute:"","left-0":"","top-0":"",transform:"translate-y-[-100%]","w-full":""}),F("div",c0,[ke(H(hs),{modelValue:e.value,"onUpdate:modelValue":T[0]||(T[0]=I=>e.value=I),placeholder:H(f)("stage.message"),border:"solid 2 primary-100 dark:primary-400/20",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500 placeholder:primary-300 placeholder:hover:primary-500 placeholder:dark:primary-300/50 placeholder:dark:hover:primary-500",bg:"primary-100 dark:primary-400/20","max-h":"[10lh]","min-h":"[1lh]","w-full":"","resize-none":"","overflow-y-scroll":"","rounded-xl":"","p-2":"","font-medium":"","outline-none":"",transition:"all duration-250 ease-in-out placeholder:all placeholder:duration-250 placeholder:ease-in-out",class:at({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:p},null,8,["modelValue","placeholder","class"])])])]))}}),d0={class:"relative"},p0={absolute:"","left-0":"","right-0":"","top-0":"","w-full":"","overflow-hidden":""},h0=Fe({__name:"AnimatedWave",props:{height:{default:40},amplitude:{default:14},waveLength:{default:250},fillColor:{default:"oklch(95% 0.10 var(--theme-colors-hue))"},direction:{default:"down"},movementDirection:{default:"left"},animationSpeed:{default:50}},setup(t){const e=t,n=W(e.height),r=W(e.amplitude),i=W(e.waveLength),o=W(e.fillColor),s=W(e.direction),a=W(e.movementDirection);function l(f,p,d,b,x){const v=[],I=Math.ceil(f/b)*b,_=1,C=x==="up"?d:p-d;v.push(`M 0 ${C}`);const P=Math.PI*2/b;for(let M=0;M<=I;M+=_){const y=d*Math.sin(P*M),g=x==="up"?C-y:C+y;v.push(`L ${M} ${g}`)}const h=x==="up"?p:0;return v.push(`L ${I} ${h}`),v.push(`L 0 ${h} Z`),v.join(" ")}const u=Ue(()=>n.value+r.value*2),c=Ue(()=>{const f=` - - `;return`url(data:image/svg+xml;base64,${btoa(f)})`});return je(()=>[e.height,e.amplitude,e.waveLength,e.fillColor,e.direction,e.movementDirection],()=>{n.value=e.height,r.value=e.amplitude,i.value=e.waveLength,o.value=e.fillColor,s.value=e.direction,a.value=e.movementDirection},{immediate:!0}),(f,p)=>(ee(),ie("div",d0,[gn(f.$slots,"default",{},void 0,!0),F("div",p0,[F("div",{class:"wave",style:Dr({background:o.value,height:`${u.value}px`,maskImage:c.value,WebkitMaskImage:c.value,"--wave-translate":`${-i.value}px`,"--animation-duration":`${i.value/t.animationSpeed}s`,"animation-direction":a.value==="left"?"normal":"reverse"})},null,4)])]))}}),m0=Kn(h0,[["__scopeId","data-v-d4cf94d8"]]),g0={relative:"",flex:"~ col","z-2":"","h-100dvh":"","w-100vw":"","of-hidden":""},y0={relative:"",flex:"~ 1 row gap-y-0 gap-x-2 (ee(),Qt(Zg,null,{default:Be(()=>[ke(m0,{"fill-color":H(e)?"oklch(35% calc(var(--theme-colors-chroma) * 0.6) var(--theme-colors-hue))":"color-mix(in srgb, oklch(95% calc(var(--theme-colors-chroma-50) * 0.5) var(--theme-colors-hue)) 80%, oklch(100% 0 360))"},{default:Be(()=>[F("div",g0,[F("div",null,[ke(ty,{class:"flex",p2:""})]),F("div",y0,[ke(H(Kg),{"flex-1":"","min-w":"1/2",paused:n.value},null,8,["paused"]),ke(Xy,{class:"flex "u"||t.call(u,p)},a=function(u,c){n&&c.name==="__proto__"?n(u,c.name,{enumerable:!0,configurable:!0,value:c.newValue,writable:!0}):u[c.name]=c.newValue},s=function(u,c){if(c==="__proto__")if(t.call(u,c)){if(r)return r(u,c).value}else return;return u[c]};return _r=function l(){var u,c,f,p,d,b,x=arguments[0],v=1,T=arguments.length,I=!1;for(typeof x=="boolean"&&(I=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});va.length;let l;s&&a.push(i);try{l=t.apply(this,a)}catch(u){const c=u;if(s&&n)throw c;return i(c)}s||(l&&l.then&&typeof l.then=="function"?l.then(o,i):l instanceof Error?i(l):o(l))}function i(a,...s){n||(n=!0,e(a,...s))}function o(a){i(null,a)}}class We extends Error{constructor(e,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let i="",o={},a=!1;if(n&&("line"in n&&"column"in n?o={place:n}:"start"in n&&"end"in n?o={place:n}:"type"in n?o={ancestors:[n],place:n.position}:o={...n}),typeof e=="string"?i=e:!o.cause&&e&&(a=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof r=="string"){const l=r.indexOf(":");l===-1?o.ruleId=r:(o.source=r.slice(0,l),o.ruleId=r.slice(l+1))}if(!o.place&&o.ancestors&&o.ancestors){const l=o.ancestors[o.ancestors.length-1];l&&(o.place=l.position)}const s=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=s?s.column:void 0,this.fatal=void 0,this.file,this.message=i,this.line=s?s.line:void 0,this.name=dn(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=a&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual,this.expected,this.note,this.url}}We.prototype.file="";We.prototype.name="";We.prototype.reason="";We.prototype.message="";We.prototype.stack="";We.prototype.column=void 0;We.prototype.line=void 0;We.prototype.ancestors=void 0;We.prototype.cause=void 0;We.prototype.fatal=void 0;We.prototype.place=void 0;We.prototype.ruleId=void 0;We.prototype.source=void 0;const lt={basename:_g,dirname:Ag,extname:Eg,join:Mg,sep:"/"};function _g(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');wn(t);let n=0,r=-1,i=t.length,o;if(e===void 0||e.length===0||e.length>t.length){for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else r<0&&(o=!0,r=i+1);return r<0?"":t.slice(n,r)}if(e===t)return"";let a=-1,s=e.length-1;for(;i--;)if(t.codePointAt(i)===47){if(o){n=i+1;break}}else a<0&&(o=!0,a=i+1),s>-1&&(t.codePointAt(i)===e.codePointAt(s--)?s<0&&(r=i):(s=-1,r=a));return n===r?r=a:r<0&&(r=t.length),t.slice(n,r)}function Ag(t){if(wn(t),t.length===0)return".";let e=-1,n=t.length,r;for(;--n;)if(t.codePointAt(n)===47){if(r){e=n;break}}else r||(r=!0);return e<0?t.codePointAt(0)===47?"/":".":e===1&&t.codePointAt(0)===47?"//":t.slice(0,e)}function Eg(t){wn(t);let e=t.length,n=-1,r=0,i=-1,o=0,a;for(;e--;){const s=t.codePointAt(e);if(s===47){if(a){r=e+1;break}continue}n<0&&(a=!0,n=e+1),s===46?i<0?i=e:o!==1&&(o=1):i>-1&&(o=-1)}return i<0||n<0||o===0||o===1&&i===n-1&&i===r+1?"":t.slice(i,n)}function Mg(...t){let e=-1,n;for(;++e0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function Ig(t,e){let n="",r=0,i=-1,o=0,a=-1,s,l;for(;++a<=t.length;){if(a2){if(l=n.lastIndexOf("/"),l!==n.length-1){l<0?(n="",r=0):(n=n.slice(0,l),r=n.length-1-n.lastIndexOf("/")),i=a,o=0;continue}}else if(n.length>0){n="",r=0,i=a,o=0;continue}}e&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+t.slice(i+1,a):n=t.slice(i+1,a),r=a-i-1;i=a,o=0}else s===46&&o>-1?o++:o=-1}return n}function wn(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const Rg={cwd:Cg};function Cg(){return"/"}function Qr(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function Ng(t){if(typeof t=="string")t=new URL(t);else if(!Qr(t)){const e=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw e.code="ERR_INVALID_ARG_TYPE",e}if(t.protocol!=="file:"){const e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return Lg(t)}function Lg(t){if(t.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const e=t.pathname;let n=-1;for(;++n0){let[d,...b]=c;const x=r[p][1];Xr(x)&&Xr(d)&&(d=Ar(!0,x,d)),r[p]=[u,d,...b]}}}}const Fg=new _i().freeze();function Ir(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Rr(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Cr(t,e){if(e)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Yo(t){if(!Xr(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Ko(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function Nn(t){return Bg(t)?t:new Pg(t)}function Bg(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function Ug(t){return typeof t=="string"||jg(t)}function jg(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}function Ai(){const t=Fg().use(Tm).use(vg).use(gp);return{process:e=>t.processSync(e).toString()}}const Vg={relative:""},Hg={"h-full":"","w-full":""},Gg={key:0,class:"animate-stripe",absolute:"",left:"1/2",bottom:"20%",z:"20","rounded-2xl":"",text:"primary-600","px-2":"","py-2":"",transform:"translate-x--1/2"},$g={bg:"primary-50","rounded-xl":"","px-10":"","py-6":""},qg=["innerHTML"],Yg=ze({__name:"Stage",props:{paused:{type:Boolean,default:!1}},setup(t){const e=W(),n=W(),{stageView:r}=Ze(Xt()),{mouthOpenSize:i}=Ze(iu()),{audioContext:o,calculateVolume:a}=ga(),{onBeforeMessageComposed:s,onBeforeSend:l,onTokenLiteral:u,onTokenSpecial:c,onStreamEnd:f,streamingMessage:p,onAssistantResponseEnd:d}=St(),{process:b}=Ai(),x=ui(),v=W(),T=W(!1),I=W(!1),A=or({handlers:[_=>new Promise(te=>{const ce=o.createBufferSource();ce.buffer=_.data.audioBuffer,ce.connect(o.destination),ce.connect(v.value),T.value=!0,ce.start(0),ce.onended=()=>{T.value=!1,te()}})]}),C=Bl(),{ssmlEnabled:P,activeSpeechProvider:h,activeSpeechModel:S,activeSpeechVoice:y,pitch:g}=Ze(C);async function m(_){try{if(!h.value){console.warn("No active speech provider configured");return}if(!y.value){console.warn("No active speech voice configured");return}const te=x.getProviderInstance(h.value);if(!te){console.error("Failed to initialize speech provider");return}const ce=x.getProviderConfig(h.value),R=P.value?C.generateSSML(_.data,y.value,{...ce,pitch:g.value}):_.data,pe=await Ul({...te.speech(S.value,ce),input:R,voice:y.value.id}),ye=await o.decodeAudioData(pe);await A.add({audioBuffer:ye,text:_.data})}catch(te){console.error("Speech generation failed:",te)}}const k=or({handlers:[m]});k.on("add",_=>{console.debug("ttsQueue added",_)});const E=jl(k),{live2dCurrentMotion:O}=Ze(Xt()),F=or({handlers:[async _=>{if(r.value==="3d"){const te=Ps[_.data];if(!te)return;await n.value.setExpression(te)}else r.value==="2d"&&(O.value={group:Ds[_.data]})}]}),D=Vl(F);D.onHandlerEvent("emotion",_=>{console.debug("emotion detected",_)});const B=Hl();B.onHandlerEvent("delay",_=>{console.debug("delay detected",_)});function X(){requestAnimationFrame(X),T.value&&(i.value=a(v.value,"linear"))}function Z(){I.value||(X(),o.resume(),I.value=!0)}function Q(){v.value||(v.value=o.createAnalyser())}return s(async()=>{Q(),Z()}),l(async()=>{O.value={group:Si}}),u(async _=>{await E.add(_)}),c(async _=>{await B.add(_),await D.add(_)}),f(async()=>{await B.add(Gl)}),d(async _=>{}),zt(()=>{var te,ce,R;I.value=!1;const _=window;(te=_.electron)==null||te.ipcRenderer.removeAllListeners("before-hide"),(ce=_.electron)==null||ce.ipcRenderer.removeAllListeners("after-show"),(R=_.electron)==null||R.ipcRenderer.removeAllListeners("before-quit")}),pn(()=>{var te,ce,R;const _=window;(te=_.electron)==null||te.ipcRenderer.on("before-hide",()=>{O.value={group:Rs}}),(ce=_.electron)==null||ce.ipcRenderer.on("after-show",()=>{O.value={group:Cs}}),(R=_.electron)==null||R.ipcRenderer.on("before-quit",()=>{O.value={group:Si}})}),pn(async()=>{e.value=Ns("duckdb-wasm://?bundles=import-url"),await e.value.execute(Ls`CREATE TABLE memory_test (vec FLOAT[768]);`)}),(_,te)=>(ee(),ie("div",Vg,[z("div",Hg,[H(r)==="2d"?(ee(),Qt(wu,{key:0,"mouth-open-size":H(i),"min-w":"50% (ee(),ie("header",Jg,[z("div",ey,[ke(Jl)]),ke(H(Cl),{class:"m-1 block max-h-[10lh] min-h-[1lh] rounded-lg bg-zinc-100 p-2 text-lg text-zinc-500 outline-none dark:bg-zinc-800 dark:text-zinc-400",to:"/settings"},{default:Be(()=>n[0]||(n[0]=[z("div",{"i-solar:settings-minimalistic-bold-duotone":""},null,-1)])),_:1})]))}});function ws(t,e){const n=fa(e??{},{...zi.getDefaultRealTimeVADOptions("v5"),preSpeechPadFrames:30,positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,minSpeechFrames:30,auto:!0}),r=W(),i=Nl("microphone");async function o(){if(r.value&&(r.value.destroy(),r.value=void 0,console.warn("existing MicVAD destroyed")),!i.value)return;const a=H(t);if(!a)return;const s=await navigator.mediaDevices.getUserMedia({audio:{deviceId:a}});r.value=await zi.MicVAD.new({...n,stream:s}),n.auto&&r.value.start()}return je(i,o,{immediate:!0}),je(Ll(t),o,{immediate:!0}),Pl(o),zt(()=>{r.value&&(r.value.destroy(),r.value=void 0)}),{destroy:()=>{r.value&&(r.value.destroy(),r.value=void 0)},start:()=>{r.value&&r.value.start()}}}function ny(t,e){const n=fa(e,{onLoading:()=>{},onInitiate:()=>{},onProgress:()=>{},onDone:()=>{},onReady:()=>{},onStart:()=>{},onUpdate:()=>{},onComplete:()=>{}}),{post:r,data:i,terminate:o}=Dl(t,{type:"module"}),a=W(null),s=W(""),l=W([]),u=W(!1),c=W(0),f=W("");return je(i,p=>{var d,b,x,v,T,I,A,C;switch(p.status){case"loading":a.value="loading",s.value=p.data,(d=n.onLoading)==null||d.call(n,p.data);break;case"initiate":l.value.push(p),(b=n.onInitiate)==null||b.call(n,p);break;case"progress":l.value=l.value.map(P=>P.file===p.file?{...P,...p}:P),(x=n.onProgress)==null||x.call(n,p);break;case"done":l.value=l.value.filter(P=>P.file!==p.file),(v=n.onDone)==null||v.call(n,p);break;case"ready":a.value="ready",(T=n.onReady)==null||T.call(n);break;case"start":u.value=!0,(I=n.onStart)==null||I.call(n);break;case"update":c.value=p.tps,(A=n.onUpdate)==null||A.call(n,p.tps);break;case"complete":u.value=!1,f.value=p.output[0]||"",console.debug("Whisper result:",f.value),(C=n.onComplete)==null||C.call(n,p.output[0]);break}}),zt(()=>{o()}),{transcribe:p=>r(p),status:a,loadingMessage:s,loadingProgress:l,transcribing:u,tps:c,result:f,load:()=>r({type:"load"}),terminate:o}}const ry="/assets/worker-D9VCBMJ0.js";async function iy(t,e){const n=new ArrayBuffer(44+t.length*2),r=new DataView(n);Ln(r,0,"RIFF"),r.setUint32(4,36+t.length*2,!0),Ln(r,8,"WAVE"),Ln(r,12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,e,!0),r.setUint32(28,e*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),Ln(r,36,"data"),r.setUint32(40,t.length*2,!0),oy(r,44,t);const i=new Blob([r],{type:"audio/wav"});return new Promise((o,a)=>{const s=new FileReader;s.onload=()=>{const l=s.result.split(",")[1];o(l)},s.onerror=a,s.readAsDataURL(i)})}function Ln(t,e,n){for(let r=0;r{jn().then(()=>{i.update(),o.value=i.height.value})}),u(async()=>{jn().then(()=>{i.update(),o.value=i.height.value})}),(c,f)=>{const p=pa("auto-animate");return ee(),ie("div",ay,[f[2]||(f[2]=z("div",{"flex-1":""},null,-1)),At((ee(),ie("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"",flex:"~ col","overflow-scroll":""},[f[1]||(f[1]=z("div",{"flex-1":""},null,-1)),(ee(!0),ie(si,null,li(H(n),(d,b)=>(ee(),ie("div",{key:b,"mb-2":""},[d.role==="error"?(ee(),ie("div",sy,[z("div",ly,[z("div",uy,[z("div",cy,[z("span",fy,ge(H(a)("stage.chat.message.character-name.core-system")),1)]),f[0]||(f[0]=z("div",{"i-solar:danger-triangle-bold-duotone":"","text-violet-500":""},null,-1))]),H(r)?(ee(),ie("div",dy)):(ee(),ie("div",{key:1,class:"markdown-content break-words text-violet-500",text:"base {if(!E||!E.trim())return;const O=o.getProviderConfig(a.value);await d(E,{chatProvider:o.getProviderInstance(a.value),model:s.value,providerConfig:O})}});async function h(){if(e.value.trim())try{const E=o.getProviderConfig(a.value);await d(e.value,{chatProvider:o.getProviderInstance(a.value),model:s.value,providerConfig:E})}catch(E){x.value.pop(),x.value.push({role:"error",content:E.message})}}const{destroy:S,start:y}=ws(p,{onSpeechStart:()=>{n.value=!0},onVADMisfire:()=>{n.value=!1},onSpeechEnd:E=>{n.value=!1,m(E)},auto:!1});function g(){C.value!=="loading"&&(A(),y())}async function m(E){await v.resume();const O=await iy(E,v.sampleRate);I({type:"generate",data:{audio:O,language:"en"}})}async function k(E){const O=E.target,F=u.value.find(D=>D.deviceId===O.value);if(!F){c.value=void 0;return}c.value=F}return je(f,async E=>{E==="false"&&(S(),P())}),b(async()=>{e.value=""}),(E,O)=>(ee(),ie("div",Ay,[z("fieldset",Ey,[z("label",{class:st([r.value==="chat"?"bg-primary-100 dark:bg-primary-900":"bg-white dark:bg-primary-950",r.value==="chat"?"text-primary-500 dark:text-primary-500":"",{"transition-colors-none ":H(l)}]),flex:"~ row",checked:r.value==="chat","aria-checked":r.value==="chat",border:"solid l-2 t-2 b-2 primary-100 dark:primary-900",bg:"hover:primary-100 dark:hover:primary-900",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500",transition:"all duration-250 ease-in-out","cursor-pointer":"","items-center":"","gap-1":"","rounded-l-lg":"","px-2":""},[At(z("input",{"onUpdate:modelValue":O[0]||(O[0]=F=>r.value=F),type:"radio",name:"tab",value:"chat",hidden:""},null,512),[[ir,r.value]]),O[5]||(O[5]=z("div",{"i-solar:dialog-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),z("div",Sy,[z("span",Iy,ge(H(T)("stage.chat.tabs.chat")),1)])],10,My),z("label",{class:st([r.value==="custom"?"bg-primary-100 dark:bg-primary-900":"bg-white dark:bg-primary-950",r.value==="custom"?"text-primary-500 dark:text-primary-500":"",{"transition-colors-none ":H(l)}]),flex:"~ row",checked:r.value==="custom","aria-checked":r.value==="custom",border:"solid t-2 b-2 primary-100 dark:primary-900",bg:"hover:primary-100 dark:hover:primary-900",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500",transition:"all duration-250 ease-in-out","cursor-pointer":"","items-center":"","gap-1":"","px-2":""},[At(z("input",{"onUpdate:modelValue":O[1]||(O[1]=F=>r.value=F),type:"radio",name:"tab",value:"custom",hidden:""},null,512),[[ir,r.value]]),O[6]||(O[6]=z("div",{"i-solar:star-fall-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),z("div",Cy,[z("span",null,ge(H(T)("stage.chat.tabs.custom")),1)])],10,Ry),z("label",{class:st([r.value==="clothes"?"bg-primary-100 dark:bg-primary-900":"bg-white dark:bg-primary-950",r.value==="clothes"?"text-primary-500 dark:text-primary-500":"",{"transition-colors-none ":H(l)}]),flex:"~ row",checked:r.value==="clothes","aria-checked":r.value==="clothes",border:"solid r-2 t-2 b-2 primary-100 dark:primary-900",bg:"hover:primary-100 dark:hover:primary-900",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500",transition:"all duration-250 ease-in-out","cursor-pointer":"","items-center":"","gap-1":"","rounded-r-lg":"","px-2":""},[At(z("input",{"onUpdate:modelValue":O[2]||(O[2]=F=>r.value=F),type:"radio",name:"tab",value:"clothes",hidden:""},null,512),[[ir,r.value]]),O[7]||(O[7]=z("div",{"i-solar:magic-stick-3-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),z("div",Ly,[z("span",null,ge(H(T)("stage.chat.tabs.clothes")),1)])],10,Ny)]),z("div",Py,[z("div",Dy,[ke(_y,{"h-full":"","flex-1":"","p-4":"",w:"full","max-h":"e.value=F),placeholder:H(T)("stage.message"),text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500 placeholder:primary-300 placeholder:hover:primary-500 placeholder:dark:primary-300/50 placeholder:dark:hover:primary-500",bg:"primary-100 dark:primary-400/20","min-h":"[100px]","max-h":"[300px]","w-full":"","rounded-t-xl":"","p-4":"","font-medium":"","outline-none":"",transition:"all duration-250 ease-in-out placeholder:all placeholder:duration-250 placeholder:ease-in-out",class:st({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:h},null,8,["modelValue","placeholder","class"])])])]),z("div",zy,[z("button",{bg:"complementary-100 hover:complementary-200 dark:complementary-800 dark:hover:complementary-700",transition:"all duration-250 ease-in-out",class:st({"transition-colors-none":H(l)}),text:"complementary-400","mb-6":"",flex:"","cursor-pointer":"","items-center":"","justify-center":"","gap-2":"","rounded-full":"","px-4":"","py-2":"",onClick:g},[ke(zl,{mode:"out-in"},{default:Be(()=>[H(C)===null?(ee(),ie("div",Fy,ge(H(T)("stage.operations.load-models")),1)):H(C)==="loading"?(ee(),ie("div",By,[O[8]||(O[8]=z("div",{"i-svg-spinners:bouncing-ball":"",class:"text-cyan"},null,-1)),z("span",null,ge(H(T)("stage.operations.load-models-status.loading")),1)])):H(C)==="ready"?(ee(),ie("div",Uy,[O[9]||(O[9]=z("div",{"i-lucide:check":"",class:"text-cyan"},null,-1)),z("span",null,ge(H(T)("stage.operations.load-models-status.ready")),1)])):it("",!0)]),_:1})],2),z("div",jy,[ke(H(ci),null,{default:Be(()=>[i.value?(ee(),ie("fieldset",Vy,[(ee(!0),ie(si,null,li(H(u),(F,D)=>(ee(),ie("label",{key:D,class:"[&_div_span]:dark:hover:bg-cyan-300 [&_div_span]:dark:hover:bg-cyan-900"},[z("input",{type:"radio",name:"audioInput",value:F.deviceId,hidden:"",onChange:k},null,40,Hy),z("div",Gy,[z("div",$y,[F.deviceId===H(p)?(ee(),ie("div",qy)):it("",!0)]),z("span",{"inline-block":"",class:st([F.deviceId===H(p)?"cyan-400 dark:text-white":"cyan-400/50 dark:text-white/50"]),transition:"all duration-250 ease-in-out"},ge(F.label),3)])]))),128))])):it("",!0)]),_:1}),z("label",{bg:"complementary-100 hover:complementary-200 dark:complementary-800 dark:hover:complementary-700",transition:"all duration-250 ease-in-out",class:st({"transition-colors-none":H(l)}),text:"complementary-400","mb-6":"",flex:"","cursor-pointer":"","items-center":"","justify-center":"","gap-2":"","rounded-full":"","px-4":"","py-2":""},[At(z("input",{"onUpdate:modelValue":O[4]||(O[4]=F=>i.value=F),type:"checkbox",hidden:""},null,512),[[Jr,i.value]]),O[10]||(O[10]=z("div",{"i-solar:microphone-2-bold-duotone":""},null,-1)),z("div",null,[n.value?(ee(),ie("span",Ky,"Listening...")):(ee(),ie("span",Yy,ge(H(T)("settings.microphone")),1))])],2)])])]))}}),Xy=Kn(Wy,[["__scopeId","data-v-0b41b5bf"]]),Qy={py:"1",flex:"~ col",rounded:"lg","overflow-hidden":""},Zy={key:0,flex:"",mr:"12"},Jy={flex:"~ col",border:"4 solid primary-200/50 dark:primary-500/50",shadow:"md primary-200/50 dark:none","min-w-20":"","rounded-lg":"","px-2":"","py-1":"",h:"unset {jn().then(()=>{i.update(),o.value=i.height.value})}),l(async()=>{jn().then(()=>{i.update(),o.value=i.height.value})}),(u,c)=>{const f=pa("auto-animate");return ee(),ie("div",Qy,[c[1]||(c[1]=z("div",{"flex-1":""},null,-1)),At((ee(),ie("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"","max-h":"30vh",flex:"~ col","overflow-scroll":""},[c[0]||(c[0]=z("div",{"flex-1":""},null,-1)),(ee(!0),ie(si,null,li(H(r),(p,d)=>(ee(),ie("div",{key:d,"mb-2":""},[p.role==="assistant"?(ee(),ie("div",Zy,[z("div",Jy,[z("div",null,[z("span",e0,ge(H(n)("stage.chat.message.character-name.airi")),1)]),p.content?(ee(),ie("div",{key:0,class:"markdown-content",text:"base {n.value=!0},onVADMisfire:()=>{n.value=!1},onSpeechEnd:v=>{n.value=!1,x()},auto:!1});function x(v){alert("Transcription is not implemented yet")}return je(a,async v=>{v==="false"&&d()}),c(async()=>{e.value=""}),pn(()=>{b()}),(v,T)=>(ee(),ie("div",null,[z("div",u0,[ke(l0,{absolute:"","left-0":"","top-0":"",transform:"translate-y-[-100%]","w-full":""}),z("div",c0,[ke(H(ha),{modelValue:e.value,"onUpdate:modelValue":T[0]||(T[0]=I=>e.value=I),placeholder:H(f)("stage.message"),border:"solid 2 primary-100 dark:primary-400/20",text:"primary-300 hover:primary-500 dark:primary-300/50 dark:hover:primary-500 placeholder:primary-300 placeholder:hover:primary-500 placeholder:dark:primary-300/50 placeholder:dark:hover:primary-500",bg:"primary-100 dark:primary-400/20","max-h":"[10lh]","min-h":"[1lh]","w-full":"","resize-none":"","overflow-y-scroll":"","rounded-xl":"","p-2":"","font-medium":"","outline-none":"",transition:"all duration-250 ease-in-out placeholder:all placeholder:duration-250 placeholder:ease-in-out",class:st({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:p},null,8,["modelValue","placeholder","class"])])])]))}}),d0={class:"relative"},p0={absolute:"","left-0":"","right-0":"","top-0":"","w-full":"","overflow-hidden":""},h0=ze({__name:"AnimatedWave",props:{height:{default:40},amplitude:{default:14},waveLength:{default:250},fillColor:{default:"oklch(95% 0.10 var(--theme-colors-hue))"},direction:{default:"down"},movementDirection:{default:"left"},animationSpeed:{default:50}},setup(t){const e=t,n=W(e.height),r=W(e.amplitude),i=W(e.waveLength),o=W(e.fillColor),a=W(e.direction),s=W(e.movementDirection);function l(f,p,d,b,x){const v=[],I=Math.ceil(f/b)*b,A=1,C=x==="up"?d:p-d;v.push(`M 0 ${C}`);const P=Math.PI*2/b;for(let S=0;S<=I;S+=A){const y=d*Math.sin(P*S),g=x==="up"?C-y:C+y;v.push(`L ${S} ${g}`)}const h=x==="up"?p:0;return v.push(`L ${I} ${h}`),v.push(`L 0 ${h} Z`),v.join(" ")}const u=Ue(()=>n.value+r.value*2),c=Ue(()=>{const f=` + + `;return`url(data:image/svg+xml;base64,${btoa(f)})`});return je(()=>[e.height,e.amplitude,e.waveLength,e.fillColor,e.direction,e.movementDirection],()=>{n.value=e.height,r.value=e.amplitude,i.value=e.waveLength,o.value=e.fillColor,a.value=e.direction,s.value=e.movementDirection},{immediate:!0}),(f,p)=>(ee(),ie("div",d0,[gn(f.$slots,"default",{},void 0,!0),z("div",p0,[z("div",{class:"wave",style:Dr({background:o.value,height:`${u.value}px`,maskImage:c.value,WebkitMaskImage:c.value,"--wave-translate":`${-i.value}px`,"--animation-duration":`${i.value/t.animationSpeed}s`,"animation-direction":s.value==="left"?"normal":"reverse"})},null,4)])]))}}),m0=Kn(h0,[["__scopeId","data-v-d4cf94d8"]]),g0={relative:"",flex:"~ col","z-2":"","h-100dvh":"","w-100vw":"","of-hidden":""},y0={relative:"",flex:"~ 1 row gap-y-0 gap-x-2 (ee(),Qt(Zg,null,{default:Be(()=>[ke(m0,{"fill-color":H(e)?"oklch(35% calc(var(--theme-colors-chroma) * 0.6) var(--theme-colors-hue))":"color-mix(in srgb, oklch(95% calc(var(--theme-colors-chroma-50) * 0.5) var(--theme-colors-hue)) 80%, oklch(100% 0 360))"},{default:Be(()=>[z("div",g0,[z("div",null,[ke(ty,{class:"flex",p2:""})]),z("div",y0,[ke(H(Kg),{"flex-1":"","min-w":"1/2",paused:n.value},null,8,["paused"]),ke(Xy,{class:"flex {const a=d("motion");return p((u(),_("div",x,[t("button",{onClick:e[0]||(e[0]=g=>o(i).back())},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",m,[t("div",v,[t("span",f,n(o(s)("settings.title")),1)]),t("div",b,n(o(s)("settings.pages.memory.title")),1)])])),[[a]])}}});export{h as default}; +import{d as r,bE as l,i as c,bw as d,A as p,o as u,c as _,a as t,e as o,D as n}from"./index-Dlp4W1Zl.js";const x={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},m={relative:""},v={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},f={text:"neutral-300 dark:neutral-500","text-nowrap":""},b={"text-nowrap":"","text-3xl":"","font-semibold":""},h=r({__name:"index",setup(w){const i=l(),{t:s}=c();return(y,e)=>{const a=d("motion");return p((u(),_("div",x,[t("button",{onClick:e[0]||(e[0]=g=>o(i).back())},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",m,[t("div",v,[t("span",f,n(o(s)("settings.title")),1)]),t("div",b,n(o(s)("settings.pages.memory.title")),1)])])),[[a]])}}});export{h as default}; diff --git a/assets/index-rD0Uu1v9.js b/assets/index-Dlp4W1Zl.js similarity index 99% rename from assets/index-rD0Uu1v9.js rename to assets/index-Dlp4W1Zl.js index a8be92db69e33c41adea50cea623dead94be1ccb..00ff23ce9f88fa63c0ccc3058db090a927c1c4c9 100644 --- a/assets/index-rD0Uu1v9.js +++ b/assets/index-Dlp4W1Zl.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-Dqf43m-t.js","assets/HeaderLink-0aZMXKsY.js","assets/HeaderLink-DsxHr3rn.css","assets/index-0FtS8e47.js","assets/live2d-zip-loader-BdiFCiUD.js","assets/speech-CUKri9wm.js","assets/providers-Dg3FpvfZ.js","assets/queue-EbaGahVd.js","assets/queues-kGVt0l-U.js","assets/Model.vue_vue_type_script_setup_true_lang-DfGKadm0.js","assets/TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js","assets/Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js","assets/consciousness-B-O47Lyx.js","assets/index-0_JGTbws.js","assets/route-block-B_A1xBdJ.js","assets/index-B6DQ8quC.css","assets/image-B7AzUr5g.js","assets/image-BhuwcwI9.css","assets/queue-CdKSGkpu.js","assets/index-BNrxdvv8.js","assets/IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js","assets/index-_olT-Lql.css","assets/index-DEIl8OlI.js","assets/Section.vue_vue_type_script_setup_true_lang-BtOV76U1.js","assets/useIconAnimation-BDdHp70p.js","assets/index-BYyZqaKb.css","assets/index-Du8ix7FM.js","assets/index-Db_5cqsO.css","assets/index-zxlyBIy_.js","assets/IconStatusItem-BolEMtws.js","assets/IconStatusItem-CA5Z6Ako.css","assets/consciousness-B3RqLnFs.js","assets/RadioCardDetailManySelect-cGsz75Pf.js","assets/Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js","assets/RadioCardDetailManySelect-DElBmhgy.css","assets/speech-BAXAx1sa.js","assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js","assets/TestDummyMarker-vebZ6Nf0.css","assets/FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js","assets/speech-Hr-CnTW2.css","assets/index-d-t5NO1c.js","assets/cloudflare-workers-ai-DW44wYmt.js","assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js","assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js","assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js","assets/deepseek-C0RKjeMo.js","assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js","assets/elevenlabs-BwDmvV0f.js","assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-UpCqB8UJ.js","assets/fireworks-ai-DLDw3hxW.js","assets/microsoft-speech-CbKBRvT-.js","assets/mistral-ai-BSvPWWKn.js","assets/moonshot-ai-BpNd7lqk.js","assets/novita-ai-CMr47yM2.js","assets/ollama-CxlTq2Yg.js","assets/openai-aA-L1GVd.js","assets/openrouter-ai-DCnIiw2z.js","assets/together-ai-DTW1P193.js","assets/xai-CcYrpCYf.js","assets/delays-BG_vAngQ.js","assets/emotions-cpITk8zy.js","assets/messages-CYVaGXcj.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-BiDUV3xY.js","assets/HeaderLink-Dg_3MlXg.js","assets/HeaderLink-DsxHr3rn.css","assets/index-CgcZzzI2.js","assets/live2d-zip-loader-C5j9stxV.js","assets/speech-DU07zXBj.js","assets/providers-BRCa7xUS.js","assets/queue-DW8o1RLT.js","assets/queues-CJq1hDiQ.js","assets/Model.vue_vue_type_script_setup_true_lang-CSqfK4Nz.js","assets/TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js","assets/Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js","assets/consciousness-CnU1Bi0O.js","assets/index-YJa3XIzO.js","assets/route-block-B_A1xBdJ.js","assets/index-B6DQ8quC.css","assets/image-CD6Zjbv1.js","assets/image-BhuwcwI9.css","assets/queue-CHfe46kZ.js","assets/index-Rz4v4VGO.js","assets/IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js","assets/index-_olT-Lql.css","assets/index-ebWEHfej.js","assets/Section.vue_vue_type_script_setup_true_lang-Ju8FFDso.js","assets/useIconAnimation-DMJpspm5.js","assets/index-BYyZqaKb.css","assets/index-exdkhaXa.js","assets/index-Db_5cqsO.css","assets/index-CWukm1n3.js","assets/IconStatusItem-BxiCMDHT.js","assets/IconStatusItem-CA5Z6Ako.css","assets/consciousness-iz2nv6B3.js","assets/RadioCardDetailManySelect-rPQeY4V8.js","assets/Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js","assets/RadioCardDetailManySelect-DElBmhgy.css","assets/speech-BzDSuaZq.js","assets/TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js","assets/TestDummyMarker-D7SLWeDD.css","assets/FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js","assets/speech-Hr-CnTW2.css","assets/index-CTgzm8SA.js","assets/cloudflare-workers-ai-DV3XjoGA.js","assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js","assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js","assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js","assets/deepseek-CjDfnLNQ.js","assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js","assets/elevenlabs-3ONCU5wo.js","assets/SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-CgsOdTr3.js","assets/fireworks-ai-BpaEuc1J.js","assets/microsoft-speech-BPOz5ZLq.js","assets/mistral-ai-C7perH7S.js","assets/moonshot-ai-CZlBN-5-.js","assets/novita-ai-BTL9go8K.js","assets/ollama-qKIKZqA2.js","assets/openai-BtuP56e_.js","assets/openrouter-ai-CCt-Li_l.js","assets/together-ai-BSofzTUT.js","assets/xai-BtPhk-ua.js","assets/delays-Cwu4yMJH.js","assets/emotions-D6mNjsWQ.js","assets/messages-CT9yvwKz.js"])))=>i.map(i=>d[i]); var GA=Object.defineProperty;var WA=(n,e,t)=>e in n?GA(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var fi=(n,e,t)=>WA(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=t(r);fetch(r.href,s)}})();const XA="modulepreload",$A=function(n){return"/"+n},cv={},ut=function(e,t,i){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));r=Promise.allSettled(t.map(l=>{if(l=$A(l),l in cv)return;cv[l]=!0;const c=l.endsWith(".css"),u=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const f=document.createElement("link");if(f.rel=c?"stylesheet":XA,c||(f.as="script"),f.crossOrigin="",f.href=l,a&&f.setAttribute("nonce",a),document.head.appendChild(f),c)return new Promise((h,d)=>{f.addEventListener("load",h),f.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${l}`)))})}))}function s(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return r.then(o=>{for(const a of o||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};/** * @vue/shared v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors @@ -3846,11 +3846,11 @@ void main() { * pinia v3.0.1 * (c) 2025 Eduardo San Martin Morote * @license MIT - */let ww;const Vd=n=>ww=n,Aw=Symbol();function Hg(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var kl;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(kl||(kl={}));function _z(){const n=g0(!0),e=n.run(()=>et({}));let t=[],i=[];const r=M0({install(s){Vd(r),r._a=s,s.provide(Aw,r),s.config.globalProperties.$pinia=r,i.forEach(o=>t.push(o)),i=[]},use(s){return this._a?t.push(s):i.push(s),this},_p:t,_a:null,_e:n,_s:new Map,state:e});return r}const Cw=()=>{};function hx(n,e,t,i=Cw){n.push(e);const r=()=>{const s=n.indexOf(e);s>-1&&(n.splice(s,1),i())};return!t&&Wh()&&_0(r),r}function ia(n,...e){n.slice().forEach(t=>{t(...e)})}const vz=n=>n(),dx=Symbol(),_m=Symbol();function Gg(n,e){n instanceof Map&&e instanceof Map?e.forEach((t,i)=>n.set(i,t)):n instanceof Set&&e instanceof Set&&e.forEach(n.add,n);for(const t in e){if(!e.hasOwnProperty(t))continue;const i=e[t],r=n[t];Hg(r)&&Hg(i)&&n.hasOwnProperty(t)&&!Pt(i)&&!Cr(i)?n[t]=Gg(r,i):n[t]=i}return n}const yz=Symbol();function bz(n){return!Hg(n)||!n.hasOwnProperty(yz)}const{assign:es}=Object;function xz(n){return!!(Pt(n)&&n.effect)}function Mz(n,e,t,i){const{state:r,actions:s,getters:o}=e,a=t.state.value[n];let l;function c(){a||(t.state.value[n]=r?r():{});const u=oS(t.state.value[n]);return es(u,s,Object.keys(o||{}).reduce((f,h)=>(f[h]=M0(Se(()=>{Vd(t);const d=t._s.get(n);return o[h].call(d,d)})),f),{}))}return l=Rw(n,c,e,t,i,!0),l}function Rw(n,e,t={},i,r,s){let o;const a=es({actions:{}},t),l={deep:!0};let c,u,f=[],h=[],d;const p=i.state.value[n];!s&&!p&&(i.state.value[n]={}),et({});let _;function g(R){let x;c=u=!1,typeof R=="function"?(R(i.state.value[n]),x={type:kl.patchFunction,storeId:n,events:d}):(Gg(i.state.value[n],R),x={type:kl.patchObject,payload:R,storeId:n,events:d});const M=_=Symbol();Ss().then(()=>{_===M&&(c=!0)}),u=!0,ia(f,x,i.state.value[n])}const m=s?function(){const{state:x}=t,M=x?x():{};this.$patch(L=>{es(L,M)})}:Cw;function y(){o.stop(),f=[],h=[],i._s.delete(n)}const b=(R,x="")=>{if(dx in R)return R[_m]=x,R;const M=function(){Vd(i);const L=Array.from(arguments),F=[],V=[];function X(ee){F.push(ee)}function te(ee){V.push(ee)}ia(h,{args:L,name:M[_m],store:E,after:X,onError:te});let Z;try{Z=R.apply(this&&this.$id===n?this:E,L)}catch(ee){throw ia(V,ee),ee}return Z instanceof Promise?Z.then(ee=>(ia(F,ee),ee)).catch(ee=>(ia(V,ee),Promise.reject(ee))):(ia(F,Z),Z)};return M[dx]=!0,M[_m]=x,M},v={_p:i,$id:n,$onAction:hx.bind(null,h),$patch:g,$reset:m,$subscribe(R,x={}){const M=hx(f,R,x.detached,()=>L()),L=o.run(()=>Xe(()=>i.state.value[n],F=>{(x.flush==="sync"?u:c)&&R({storeId:n,type:kl.direct,events:d},F)},es({},l,x)));return M},$dispose:y},E=bi(v);i._s.set(n,E);const S=(i._a&&i._a.runWithContext||vz)(()=>i._e.run(()=>(o=g0()).run(()=>e({action:b}))));for(const R in S){const x=S[R];if(Pt(x)&&!xz(x)||Cr(x))s||(p&&bz(x)&&(Pt(x)?x.value=p[R]:Gg(x,p[R])),i.state.value[n][R]=x);else if(typeof x=="function"){const M=b(x,R);S[R]=M,a.actions[R]=x}}return es(E,S),es(ct(E),S),Object.defineProperty(E,"$state",{get:()=>i.state.value[n],set:R=>{g(x=>{es(x,R)})}}),i._p.forEach(R=>{es(E,o.run(()=>R({store:E,app:i._a,pinia:i,options:a})))}),p&&s&&t.hydrate&&t.hydrate(E.$state,p),c=!0,u=!0,E}/*! #__NO_SIDE_EFFECTS__ */function Sz(n,e,t){let i;const r=typeof e=="function";i=r?t:e;function s(o,a){const l=Cc();return o=o||(l?En(Aw,null):null),o&&Vd(o),o=ww,o._s.has(n)||(r?Rw(n,e,i,o):Mz(n,i,o)),o._s.get(n)}return s.$id=n,s}function Ez(n){const e=ct(n),t={};for(const i in e){const r=e[i];r.effect?t[i]=Se({get:()=>n[i],set(s){n[i]=s}}):(Pt(r)||Cr(r))&&(t[i]=aS(n,i))}return t}const Tz=n=>{const e={};Object.entries(Object.assign({"/src/layouts/default.vue":()=>ut(()=>import("./default-Dqf43m-t.js"),__vite__mapDeps([0,1,2])),"/src/layouts/stage.vue":()=>ut(()=>import("./stage-DniKT8GJ.js"),[])})).forEach(([r,s])=>{let o=r.replace("/src/layouts/","").replace(".vue","");e[o]=s});function i(r,s=!0){return r.map(o=>{var a,l,c,u,f,h;if(((a=o.children)==null?void 0:a.length)>0&&(o.children=i(o.children,!1)),s){if(!o.component&&((l=o.children)==null?void 0:l.find(p=>{var _;return(p.path===""||p.path==="/")&&((_=p.meta)==null?void 0:_.isLayout)})))return o;if(((c=o.meta)==null?void 0:c.layout)!==!1)return{path:o.path,component:e[((u=o.meta)==null?void 0:u.layout)||"default"],children:o.path==="/"?[o]:[{...o,path:""}],meta:{isLayout:!0}}}return(f=o.meta)!=null&&f.layout?{path:o.path,component:e[(h=o.meta)==null?void 0:h.layout],children:[{...o,path:""}],meta:{isLayout:!0}}:o})}return i(n)};/*! + */let ww;const Vd=n=>ww=n,Aw=Symbol();function Hg(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var kl;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(kl||(kl={}));function _z(){const n=g0(!0),e=n.run(()=>et({}));let t=[],i=[];const r=M0({install(s){Vd(r),r._a=s,s.provide(Aw,r),s.config.globalProperties.$pinia=r,i.forEach(o=>t.push(o)),i=[]},use(s){return this._a?t.push(s):i.push(s),this},_p:t,_a:null,_e:n,_s:new Map,state:e});return r}const Cw=()=>{};function hx(n,e,t,i=Cw){n.push(e);const r=()=>{const s=n.indexOf(e);s>-1&&(n.splice(s,1),i())};return!t&&Wh()&&_0(r),r}function ia(n,...e){n.slice().forEach(t=>{t(...e)})}const vz=n=>n(),dx=Symbol(),_m=Symbol();function Gg(n,e){n instanceof Map&&e instanceof Map?e.forEach((t,i)=>n.set(i,t)):n instanceof Set&&e instanceof Set&&e.forEach(n.add,n);for(const t in e){if(!e.hasOwnProperty(t))continue;const i=e[t],r=n[t];Hg(r)&&Hg(i)&&n.hasOwnProperty(t)&&!Pt(i)&&!Cr(i)?n[t]=Gg(r,i):n[t]=i}return n}const yz=Symbol();function bz(n){return!Hg(n)||!n.hasOwnProperty(yz)}const{assign:es}=Object;function xz(n){return!!(Pt(n)&&n.effect)}function Mz(n,e,t,i){const{state:r,actions:s,getters:o}=e,a=t.state.value[n];let l;function c(){a||(t.state.value[n]=r?r():{});const u=oS(t.state.value[n]);return es(u,s,Object.keys(o||{}).reduce((f,h)=>(f[h]=M0(Se(()=>{Vd(t);const d=t._s.get(n);return o[h].call(d,d)})),f),{}))}return l=Rw(n,c,e,t,i,!0),l}function Rw(n,e,t={},i,r,s){let o;const a=es({actions:{}},t),l={deep:!0};let c,u,f=[],h=[],d;const p=i.state.value[n];!s&&!p&&(i.state.value[n]={}),et({});let _;function g(R){let x;c=u=!1,typeof R=="function"?(R(i.state.value[n]),x={type:kl.patchFunction,storeId:n,events:d}):(Gg(i.state.value[n],R),x={type:kl.patchObject,payload:R,storeId:n,events:d});const M=_=Symbol();Ss().then(()=>{_===M&&(c=!0)}),u=!0,ia(f,x,i.state.value[n])}const m=s?function(){const{state:x}=t,M=x?x():{};this.$patch(L=>{es(L,M)})}:Cw;function y(){o.stop(),f=[],h=[],i._s.delete(n)}const b=(R,x="")=>{if(dx in R)return R[_m]=x,R;const M=function(){Vd(i);const L=Array.from(arguments),F=[],V=[];function X(ee){F.push(ee)}function te(ee){V.push(ee)}ia(h,{args:L,name:M[_m],store:E,after:X,onError:te});let Z;try{Z=R.apply(this&&this.$id===n?this:E,L)}catch(ee){throw ia(V,ee),ee}return Z instanceof Promise?Z.then(ee=>(ia(F,ee),ee)).catch(ee=>(ia(V,ee),Promise.reject(ee))):(ia(F,Z),Z)};return M[dx]=!0,M[_m]=x,M},v={_p:i,$id:n,$onAction:hx.bind(null,h),$patch:g,$reset:m,$subscribe(R,x={}){const M=hx(f,R,x.detached,()=>L()),L=o.run(()=>Xe(()=>i.state.value[n],F=>{(x.flush==="sync"?u:c)&&R({storeId:n,type:kl.direct,events:d},F)},es({},l,x)));return M},$dispose:y},E=bi(v);i._s.set(n,E);const S=(i._a&&i._a.runWithContext||vz)(()=>i._e.run(()=>(o=g0()).run(()=>e({action:b}))));for(const R in S){const x=S[R];if(Pt(x)&&!xz(x)||Cr(x))s||(p&&bz(x)&&(Pt(x)?x.value=p[R]:Gg(x,p[R])),i.state.value[n][R]=x);else if(typeof x=="function"){const M=b(x,R);S[R]=M,a.actions[R]=x}}return es(E,S),es(ct(E),S),Object.defineProperty(E,"$state",{get:()=>i.state.value[n],set:R=>{g(x=>{es(x,R)})}}),i._p.forEach(R=>{es(E,o.run(()=>R({store:E,app:i._a,pinia:i,options:a})))}),p&&s&&t.hydrate&&t.hydrate(E.$state,p),c=!0,u=!0,E}/*! #__NO_SIDE_EFFECTS__ */function Sz(n,e,t){let i;const r=typeof e=="function";i=r?t:e;function s(o,a){const l=Cc();return o=o||(l?En(Aw,null):null),o&&Vd(o),o=ww,o._s.has(n)||(r?Rw(n,e,i,o):Mz(n,i,o)),o._s.get(n)}return s.$id=n,s}function Ez(n){const e=ct(n),t={};for(const i in e){const r=e[i];r.effect?t[i]=Se({get:()=>n[i],set(s){n[i]=s}}):(Pt(r)||Cr(r))&&(t[i]=aS(n,i))}return t}const Tz=n=>{const e={};Object.entries(Object.assign({"/src/layouts/default.vue":()=>ut(()=>import("./default-BiDUV3xY.js"),__vite__mapDeps([0,1,2])),"/src/layouts/stage.vue":()=>ut(()=>import("./stage-DPabq-4P.js"),[])})).forEach(([r,s])=>{let o=r.replace("/src/layouts/","").replace(".vue","");e[o]=s});function i(r,s=!0){return r.map(o=>{var a,l,c,u,f,h;if(((a=o.children)==null?void 0:a.length)>0&&(o.children=i(o.children,!1)),s){if(!o.component&&((l=o.children)==null?void 0:l.find(p=>{var _;return(p.path===""||p.path==="/")&&((_=p.meta)==null?void 0:_.isLayout)})))return o;if(((c=o.meta)==null?void 0:c.layout)!==!1)return{path:o.path,component:e[((u=o.meta)==null?void 0:u.layout)||"default"],children:o.path==="/"?[o]:[{...o,path:""}],meta:{isLayout:!0}}}return(f=o.meta)!=null&&f.layout?{path:o.path,component:e[(h=o.meta)==null?void 0:h.layout],children:[{...o,path:""}],meta:{isLayout:!0}}:o})}return i(n)};/*! * vue-router v4.5.0 * (c) 2024 Eduardo San Martin Morote * @license MIT - */const sa=typeof document<"u";function Pw(n){return typeof n=="object"||"displayName"in n||"props"in n||"__vccOpts"in n}function wz(n){return n.__esModule||n[Symbol.toStringTag]==="Module"||n.default&&Pw(n.default)}const Mt=Object.assign;function vm(n,e){const t={};for(const i in e){const r=e[i];t[i]=ki(r)?r.map(n):n(r)}return t}const Bl=()=>{},ki=Array.isArray,Iw=/#/g,Az=/&/g,Cz=/\//g,Rz=/=/g,Pz=/\?/g,Lw=/\+/g,Iz=/%5B/g,Lz=/%5D/g,Dw=/%5E/g,Dz=/%60/g,Ow=/%7B/g,Oz=/%7C/g,Nw=/%7D/g,Nz=/%20/g;function B_(n){return encodeURI(""+n).replace(Oz,"|").replace(Iz,"[").replace(Lz,"]")}function Uz(n){return B_(n).replace(Ow,"{").replace(Nw,"}").replace(Dw,"^")}function Wg(n){return B_(n).replace(Lw,"%2B").replace(Nz,"+").replace(Iw,"%23").replace(Az,"%26").replace(Dz,"`").replace(Ow,"{").replace(Nw,"}").replace(Dw,"^")}function Fz(n){return Wg(n).replace(Rz,"%3D")}function kz(n){return B_(n).replace(Iw,"%23").replace(Pz,"%3F")}function Bz(n){return n==null?"":kz(n).replace(Cz,"%2F")}function bc(n){try{return decodeURIComponent(""+n)}catch{}return""+n}const zz=/\/$/,Vz=n=>n.replace(zz,"");function ym(n,e,t="/"){let i,r={},s="",o="";const a=e.indexOf("#");let l=e.indexOf("?");return a=0&&(l=-1),l>-1&&(i=e.slice(0,l),s=e.slice(l+1,a>-1?a:e.length),r=n(s)),a>-1&&(i=i||e.slice(0,a),o=e.slice(a,e.length)),i=Xz(i??e,t),{fullPath:i+(s&&"?")+s+o,path:i,query:r,hash:bc(o)}}function Hz(n,e){const t=e.query?n(e.query):"";return e.path+(t&&"?")+t+(e.hash||"")}function px(n,e){return!e||!n.toLowerCase().startsWith(e.toLowerCase())?n:n.slice(e.length)||"/"}function Gz(n,e,t){const i=e.matched.length-1,r=t.matched.length-1;return i>-1&&i===r&&Ra(e.matched[i],t.matched[r])&&Uw(e.params,t.params)&&n(e.query)===n(t.query)&&e.hash===t.hash}function Ra(n,e){return(n.aliasOf||n)===(e.aliasOf||e)}function Uw(n,e){if(Object.keys(n).length!==Object.keys(e).length)return!1;for(const t in n)if(!Wz(n[t],e[t]))return!1;return!0}function Wz(n,e){return ki(n)?mx(n,e):ki(e)?mx(e,n):n===e}function mx(n,e){return ki(e)?n.length===e.length&&n.every((t,i)=>t===e[i]):n.length===1&&n[0]===e}function Xz(n,e){if(n.startsWith("/"))return n;if(!n)return e;const t=e.split("/"),i=n.split("/"),r=i[i.length-1];(r===".."||r===".")&&i.push("");let s=t.length-1,o,a;for(o=0;o1&&s--;else break;return t.slice(0,s).join("/")+"/"+i.slice(o).join("/")}const Jr={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0};var xc;(function(n){n.pop="pop",n.push="push"})(xc||(xc={}));var zl;(function(n){n.back="back",n.forward="forward",n.unknown=""})(zl||(zl={}));function $z(n){if(!n)if(sa){const e=document.querySelector("base");n=e&&e.getAttribute("href")||"/",n=n.replace(/^\w+:\/\/[^\/]+/,"")}else n="/";return n[0]!=="/"&&n[0]!=="#"&&(n="/"+n),Vz(n)}const qz=/^[^#]+#/;function Yz(n,e){return n.replace(qz,"#")+e}function jz(n,e){const t=document.documentElement.getBoundingClientRect(),i=n.getBoundingClientRect();return{behavior:e.behavior,left:i.left-t.left-(e.left||0),top:i.top-t.top-(e.top||0)}}const Hd=()=>({left:window.scrollX,top:window.scrollY});function Kz(n){let e;if("el"in n){const t=n.el,i=typeof t=="string"&&t.startsWith("#"),r=typeof t=="string"?i?document.getElementById(t.slice(1)):document.querySelector(t):t;if(!r)return;e=jz(r,n)}else e=n;"scrollBehavior"in document.documentElement.style?window.scrollTo(e):window.scrollTo(e.left!=null?e.left:window.scrollX,e.top!=null?e.top:window.scrollY)}function gx(n,e){return(history.state?history.state.position-e:-1)+n}const Xg=new Map;function Zz(n,e){Xg.set(n,e)}function Jz(n){const e=Xg.get(n);return Xg.delete(n),e}let Qz=()=>location.protocol+"//"+location.host;function Fw(n,e){const{pathname:t,search:i,hash:r}=e,s=n.indexOf("#");if(s>-1){let a=r.includes(n.slice(s))?n.slice(s).length:1,l=r.slice(a);return l[0]!=="/"&&(l="/"+l),px(l,"")}return px(t,n)+i+r}function eV(n,e,t,i){let r=[],s=[],o=null;const a=({state:h})=>{const d=Fw(n,location),p=t.value,_=e.value;let g=0;if(h){if(t.value=d,e.value=h,o&&o===p){o=null;return}g=_?h.position-_.position:0}else i(d);r.forEach(m=>{m(t.value,p,{delta:g,type:xc.pop,direction:g?g>0?zl.forward:zl.back:zl.unknown})})};function l(){o=t.value}function c(h){r.push(h);const d=()=>{const p=r.indexOf(h);p>-1&&r.splice(p,1)};return s.push(d),d}function u(){const{history:h}=window;h.state&&h.replaceState(Mt({},h.state,{scroll:Hd()}),"")}function f(){for(const h of s)h();s=[],window.removeEventListener("popstate",a),window.removeEventListener("beforeunload",u)}return window.addEventListener("popstate",a),window.addEventListener("beforeunload",u,{passive:!0}),{pauseListeners:l,listen:c,destroy:f}}function _x(n,e,t,i=!1,r=!1){return{back:n,current:e,forward:t,replaced:i,position:window.history.length,scroll:r?Hd():null}}function tV(n){const{history:e,location:t}=window,i={value:Fw(n,t)},r={value:e.state};r.value||s(i.value,{back:null,current:i.value,forward:null,position:e.length-1,replaced:!0,scroll:null},!0);function s(l,c,u){const f=n.indexOf("#"),h=f>-1?(t.host&&document.querySelector("base")?n:n.slice(f))+l:Qz()+n+l;try{e[u?"replaceState":"pushState"](c,"",h),r.value=c}catch(d){console.error(d),t[u?"replace":"assign"](h)}}function o(l,c){const u=Mt({},e.state,_x(r.value.back,l,r.value.forward,!0),c,{position:r.value.position});s(l,u,!0),i.value=l}function a(l,c){const u=Mt({},r.value,e.state,{forward:l,scroll:Hd()});s(u.current,u,!0);const f=Mt({},_x(i.value,l,null),{position:u.position+1},c);s(l,f,!1),i.value=l}return{location:i,state:r,push:a,replace:o}}function nV(n){n=$z(n);const e=tV(n),t=eV(n,e.state,e.location,e.replace);function i(s,o=!0){o||t.pauseListeners(),history.go(s)}const r=Mt({location:"",base:n,go:i,createHref:Yz.bind(null,n)},e,t);return Object.defineProperty(r,"location",{enumerable:!0,get:()=>e.location.value}),Object.defineProperty(r,"state",{enumerable:!0,get:()=>e.state.value}),r}function iV(n){return n=location.host?n||location.pathname+location.search:"",n.includes("#")||(n+="#"),nV(n)}function rV(n){return typeof n=="string"||n&&typeof n=="object"}function kw(n){return typeof n=="string"||typeof n=="symbol"}const Bw=Symbol("");var vx;(function(n){n[n.aborted=4]="aborted",n[n.cancelled=8]="cancelled",n[n.duplicated=16]="duplicated"})(vx||(vx={}));function Pa(n,e){return Mt(new Error,{type:n,[Bw]:!0},e)}function gr(n,e){return n instanceof Error&&Bw in n&&(e==null||!!(n.type&e))}const yx="[^/]+?",sV={sensitive:!1,strict:!1,start:!0,end:!0},oV=/[.+*?^${}()[\]/\\]/g;function aV(n,e){const t=Mt({},sV,e),i=[];let r=t.start?"^":"";const s=[];for(const c of n){const u=c.length?[]:[90];t.strict&&!c.length&&(r+="/");for(let f=0;fe.length?e.length===1&&e[0]===80?1:-1:0}function zw(n,e){let t=0;const i=n.score,r=e.score;for(;t0&&e[e.length-1]<0}const cV={type:0,value:""},uV=/[a-zA-Z0-9_]/;function fV(n){if(!n)return[[]];if(n==="/")return[[cV]];if(!n.startsWith("/"))throw new Error(`Invalid path "${n}"`);function e(d){throw new Error(`ERR (${t})/"${c}": ${d}`)}let t=0,i=t;const r=[];let s;function o(){s&&r.push(s),s=[]}let a=0,l,c="",u="";function f(){c&&(t===0?s.push({type:0,value:c}):t===1||t===2||t===3?(s.length>1&&(l==="*"||l==="+")&&e(`A repeatable param (${c}) must be alone in its segment. eg: '/:ids+.`),s.push({type:1,value:c,regexp:u,repeatable:l==="*"||l==="+",optional:l==="*"||l==="?"})):e("Invalid state to consume buffer"),c="")}function h(){c+=l}for(;a{o(b)}:Bl}function o(f){if(kw(f)){const h=i.get(f);h&&(i.delete(f),t.splice(t.indexOf(h),1),h.children.forEach(o),h.alias.forEach(o))}else{const h=t.indexOf(f);h>-1&&(t.splice(h,1),f.record.name&&i.delete(f.record.name),f.children.forEach(o),f.alias.forEach(o))}}function a(){return t}function l(f){const h=gV(f,t);t.splice(h,0,f),f.record.name&&!Sx(f)&&i.set(f.record.name,f)}function c(f,h){let d,p={},_,g;if("name"in f&&f.name){if(d=i.get(f.name),!d)throw Pa(1,{location:f});g=d.record.name,p=Mt(xx(h.params,d.keys.filter(b=>!b.optional).concat(d.parent?d.parent.keys.filter(b=>b.optional):[]).map(b=>b.name)),f.params&&xx(f.params,d.keys.map(b=>b.name))),_=d.stringify(p)}else if(f.path!=null)_=f.path,d=t.find(b=>b.re.test(_)),d&&(p=d.parse(_),g=d.record.name);else{if(d=h.name?i.get(h.name):t.find(b=>b.re.test(h.path)),!d)throw Pa(1,{location:f,currentLocation:h});g=d.record.name,p=Mt({},h.params,f.params),_=d.stringify(p)}const m=[];let y=d;for(;y;)m.unshift(y.record),y=y.parent;return{name:g,path:_,params:p,matched:m,meta:mV(m)}}n.forEach(f=>s(f));function u(){t.length=0,i.clear()}return{addRoute:s,resolve:c,removeRoute:o,clearRoutes:u,getRoutes:a,getRecordMatcher:r}}function xx(n,e){const t={};for(const i of e)i in n&&(t[i]=n[i]);return t}function Mx(n){const e={path:n.path,redirect:n.redirect,name:n.name,meta:n.meta||{},aliasOf:n.aliasOf,beforeEnter:n.beforeEnter,props:pV(n),children:n.children||[],instances:{},leaveGuards:new Set,updateGuards:new Set,enterCallbacks:{},components:"components"in n?n.components||null:n.component&&{default:n.component}};return Object.defineProperty(e,"mods",{value:{}}),e}function pV(n){const e={},t=n.props||!1;if("component"in n)e.default=t;else for(const i in n.components)e[i]=typeof t=="object"?t[i]:t;return e}function Sx(n){for(;n;){if(n.record.aliasOf)return!0;n=n.parent}return!1}function mV(n){return n.reduce((e,t)=>Mt(e,t.meta),{})}function Ex(n,e){const t={};for(const i in n)t[i]=i in e?e[i]:n[i];return t}function gV(n,e){let t=0,i=e.length;for(;t!==i;){const s=t+i>>1;zw(n,e[s])<0?i=s:t=s+1}const r=_V(n);return r&&(i=e.lastIndexOf(r,i-1)),i}function _V(n){let e=n;for(;e=e.parent;)if(Vw(e)&&zw(n,e)===0)return e}function Vw({record:n}){return!!(n.name||n.components&&Object.keys(n.components).length||n.redirect)}function vV(n){const e={};if(n===""||n==="?")return e;const i=(n[0]==="?"?n.slice(1):n).split("&");for(let r=0;rs&&Wg(s)):[i&&Wg(i)]).forEach(s=>{s!==void 0&&(e+=(e.length?"&":"")+t,s!=null&&(e+="="+s))})}return e}function yV(n){const e={};for(const t in n){const i=n[t];i!==void 0&&(e[t]=ki(i)?i.map(r=>r==null?null:""+r):i==null?i:""+i)}return e}const bV=Symbol(""),wx=Symbol(""),Gd=Symbol(""),Hw=Symbol(""),$g=Symbol("");function cl(){let n=[];function e(i){return n.push(i),()=>{const r=n.indexOf(i);r>-1&&n.splice(r,1)}}function t(){n=[]}return{add:e,list:()=>n.slice(),reset:t}}function os(n,e,t,i,r,s=o=>o()){const o=i&&(i.enterCallbacks[r]=i.enterCallbacks[r]||[]);return()=>new Promise((a,l)=>{const c=h=>{h===!1?l(Pa(4,{from:t,to:e})):h instanceof Error?l(h):rV(h)?l(Pa(2,{from:e,to:h})):(o&&i.enterCallbacks[r]===o&&typeof h=="function"&&o.push(h),a())},u=s(()=>n.call(i&&i.instances[r],e,t,c));let f=Promise.resolve(u);n.length<3&&(f=f.then(c)),f.catch(h=>l(h))})}function bm(n,e,t,i,r=s=>s()){const s=[];for(const o of n)for(const a in o.components){let l=o.components[a];if(!(e!=="beforeRouteEnter"&&!o.instances[a]))if(Pw(l)){const u=(l.__vccOpts||l)[e];u&&s.push(os(u,t,i,o,a,r))}else{let c=l();s.push(()=>c.then(u=>{if(!u)throw new Error(`Couldn't resolve component "${a}" at "${o.path}"`);const f=wz(u)?u.default:u;o.mods[a]=u,o.components[a]=f;const d=(f.__vccOpts||f)[e];return d&&os(d,t,i,o,a,r)()}))}}return s}function Ax(n){const e=En(Gd),t=En(Hw),i=Se(()=>{const l=Ot(n.to);return e.resolve(l)}),r=Se(()=>{const{matched:l}=i.value,{length:c}=l,u=l[c-1],f=t.matched;if(!u||!f.length)return-1;const h=f.findIndex(Ra.bind(null,u));if(h>-1)return h;const d=Cx(l[c-2]);return c>1&&Cx(u)===d&&f[f.length-1].path!==d?f.findIndex(Ra.bind(null,l[c-2])):h}),s=Se(()=>r.value>-1&&TV(t.params,i.value.params)),o=Se(()=>r.value>-1&&r.value===t.matched.length-1&&Uw(t.params,i.value.params));function a(l={}){if(EV(l)){const c=e[Ot(n.replace)?"replace":"push"](Ot(n.to)).catch(Bl);return n.viewTransition&&typeof document<"u"&&"startViewTransition"in document&&document.startViewTransition(()=>c),c}return Promise.resolve()}return{route:i,href:Se(()=>i.value.href),isActive:s,isExactActive:o,navigate:a}}function xV(n){return n.length===1?n[0]:n}const MV=fn({name:"RouterLink",compatConfig:{MODE:3},props:{to:{type:[String,Object],required:!0},replace:Boolean,activeClass:String,exactActiveClass:String,custom:Boolean,ariaCurrentValue:{type:String,default:"page"}},useLink:Ax,setup(n,{slots:e}){const t=bi(Ax(n)),{options:i}=En(Gd),r=Se(()=>({[Rx(n.activeClass,i.linkActiveClass,"router-link-active")]:t.isActive,[Rx(n.exactActiveClass,i.linkExactActiveClass,"router-link-exact-active")]:t.isExactActive}));return()=>{const s=e.default&&xV(e.default(t));return n.custom?s:Lr("a",{"aria-current":t.isExactActive?n.ariaCurrentValue:null,href:t.href,onClick:t.navigate,class:r.value},s)}}}),SV=MV;function EV(n){if(!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)&&!n.defaultPrevented&&!(n.button!==void 0&&n.button!==0)){if(n.currentTarget&&n.currentTarget.getAttribute){const e=n.currentTarget.getAttribute("target");if(/\b_blank\b/i.test(e))return}return n.preventDefault&&n.preventDefault(),!0}}function TV(n,e){for(const t in e){const i=e[t],r=n[t];if(typeof i=="string"){if(i!==r)return!1}else if(!ki(r)||r.length!==i.length||i.some((s,o)=>s!==r[o]))return!1}return!0}function Cx(n){return n?n.aliasOf?n.aliasOf.path:n.path:""}const Rx=(n,e,t)=>n??e??t,wV=fn({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(n,{attrs:e,slots:t}){const i=En($g),r=Se(()=>n.route||i.value),s=En(wx,0),o=Se(()=>{let c=Ot(s);const{matched:u}=r.value;let f;for(;(f=u[c])&&!f.components;)c++;return c}),a=Se(()=>r.value.matched[o.value]);fs(wx,Se(()=>o.value+1)),fs(bV,a),fs($g,r);const l=et();return Xe(()=>[l.value,a.value,n.name],([c,u,f],[h,d,p])=>{u&&(u.instances[f]=c,d&&d!==u&&c&&c===h&&(u.leaveGuards.size||(u.leaveGuards=d.leaveGuards),u.updateGuards.size||(u.updateGuards=d.updateGuards))),c&&u&&(!d||!Ra(u,d)||!h)&&(u.enterCallbacks[f]||[]).forEach(_=>_(c))},{flush:"post"}),()=>{const c=r.value,u=n.name,f=a.value,h=f&&f.components[u];if(!h)return Px(t.default,{Component:h,route:c});const d=f.props[u],p=d?d===!0?c.params:typeof d=="function"?d(c):d:null,g=Lr(h,Mt({},p,e,{onVnodeUnmounted:m=>{m.component.isUnmounted&&(f.instances[u]=null)},ref:l}));return Px(t.default,{Component:g,route:c})||g}}});function Px(n,e){if(!n)return null;const t=n(e);return t.length===1?t[0]:t}const Gw=wV;function AV(n){const e=dV(n.routes,n),t=n.parseQuery||vV,i=n.stringifyQuery||Tx,r=n.history,s=cl(),o=cl(),a=cl(),l=De(Jr);let c=Jr;sa&&n.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const u=vm.bind(null,W=>""+W),f=vm.bind(null,Bz),h=vm.bind(null,bc);function d(W,ae){let ue,le;return kw(W)?(ue=e.getRecordMatcher(W),le=ae):le=W,e.addRoute(le,ue)}function p(W){const ae=e.getRecordMatcher(W);ae&&e.removeRoute(ae)}function _(){return e.getRoutes().map(W=>W.record)}function g(W){return!!e.getRecordMatcher(W)}function m(W,ae){if(ae=Mt({},ae||l.value),typeof W=="string"){const w=ym(t,W,ae.path),j=e.resolve({path:w.path},ae),G=r.createHref(w.fullPath);return Mt(w,j,{params:h(j.params),hash:bc(w.hash),redirectedFrom:void 0,href:G})}let ue;if(W.path!=null)ue=Mt({},W,{path:ym(t,W.path,ae.path).path});else{const w=Mt({},W.params);for(const j in w)w[j]==null&&delete w[j];ue=Mt({},W,{params:f(w)}),ae.params=f(ae.params)}const le=e.resolve(ue,ae),Ue=W.hash||"";le.params=u(h(le.params));const I=Hz(i,Mt({},W,{hash:Uz(Ue),path:le.path})),D=r.createHref(I);return Mt({fullPath:I,hash:Ue,query:i===Tx?yV(W.query):W.query||{}},le,{redirectedFrom:void 0,href:D})}function y(W){return typeof W=="string"?ym(t,W,l.value.path):Mt({},W)}function b(W,ae){if(c!==W)return Pa(8,{from:ae,to:W})}function v(W){return S(W)}function E(W){return v(Mt(y(W),{replace:!0}))}function T(W){const ae=W.matched[W.matched.length-1];if(ae&&ae.redirect){const{redirect:ue}=ae;let le=typeof ue=="function"?ue(W):ue;return typeof le=="string"&&(le=le.includes("?")||le.includes("#")?le=y(le):{path:le},le.params={}),Mt({query:W.query,hash:W.hash,params:le.path!=null?{}:W.params},le)}}function S(W,ae){const ue=c=m(W),le=l.value,Ue=W.state,I=W.force,D=W.replace===!0,w=T(ue);if(w)return S(Mt(y(w),{state:typeof w=="object"?Mt({},Ue,w.state):Ue,force:I,replace:D}),ae||ue);const j=ue;j.redirectedFrom=ae;let G;return!I&&Gz(i,le,ue)&&(G=Pa(16,{to:j,from:le}),re(le,le,!0,!1)),(G?Promise.resolve(G):M(j,le)).catch(q=>gr(q)?gr(q,2)?q:be(q):Q(q,j,le)).then(q=>{if(q){if(gr(q,2))return S(Mt({replace:D},y(q.to),{state:typeof q.to=="object"?Mt({},Ue,q.to.state):Ue,force:I}),ae||j)}else q=F(j,le,!0,D,Ue);return L(j,le,q),q})}function R(W,ae){const ue=b(W,ae);return ue?Promise.reject(ue):Promise.resolve()}function x(W){const ae=se.values().next().value;return ae&&typeof ae.runWithContext=="function"?ae.runWithContext(W):W()}function M(W,ae){let ue;const[le,Ue,I]=CV(W,ae);ue=bm(le.reverse(),"beforeRouteLeave",W,ae);for(const w of le)w.leaveGuards.forEach(j=>{ue.push(os(j,W,ae))});const D=R.bind(null,W,ae);return ue.push(D),Me(ue).then(()=>{ue=[];for(const w of s.list())ue.push(os(w,W,ae));return ue.push(D),Me(ue)}).then(()=>{ue=bm(Ue,"beforeRouteUpdate",W,ae);for(const w of Ue)w.updateGuards.forEach(j=>{ue.push(os(j,W,ae))});return ue.push(D),Me(ue)}).then(()=>{ue=[];for(const w of I)if(w.beforeEnter)if(ki(w.beforeEnter))for(const j of w.beforeEnter)ue.push(os(j,W,ae));else ue.push(os(w.beforeEnter,W,ae));return ue.push(D),Me(ue)}).then(()=>(W.matched.forEach(w=>w.enterCallbacks={}),ue=bm(I,"beforeRouteEnter",W,ae,x),ue.push(D),Me(ue))).then(()=>{ue=[];for(const w of o.list())ue.push(os(w,W,ae));return ue.push(D),Me(ue)}).catch(w=>gr(w,8)?w:Promise.reject(w))}function L(W,ae,ue){a.list().forEach(le=>x(()=>le(W,ae,ue)))}function F(W,ae,ue,le,Ue){const I=b(W,ae);if(I)return I;const D=ae===Jr,w=sa?history.state:{};ue&&(le||D?r.replace(W.fullPath,Mt({scroll:D&&w&&w.scroll},Ue)):r.push(W.fullPath,Ue)),l.value=W,re(W,ae,ue,D),be()}let V;function X(){V||(V=r.listen((W,ae,ue)=>{if(!ge.listening)return;const le=m(W),Ue=T(le);if(Ue){S(Mt(Ue,{replace:!0,force:!0}),le).catch(Bl);return}c=le;const I=l.value;sa&&Zz(gx(I.fullPath,ue.delta),Hd()),M(le,I).catch(D=>gr(D,12)?D:gr(D,2)?(S(Mt(y(D.to),{force:!0}),le).then(w=>{gr(w,20)&&!ue.delta&&ue.type===xc.pop&&r.go(-1,!1)}).catch(Bl),Promise.reject()):(ue.delta&&r.go(-ue.delta,!1),Q(D,le,I))).then(D=>{D=D||F(le,I,!1),D&&(ue.delta&&!gr(D,8)?r.go(-ue.delta,!1):ue.type===xc.pop&&gr(D,20)&&r.go(-1,!1)),L(le,I,D)}).catch(Bl)}))}let te=cl(),Z=cl(),ee;function Q(W,ae,ue){be(W);const le=Z.list();return le.length?le.forEach(Ue=>Ue(W,ae,ue)):console.error(W),Promise.reject(W)}function de(){return ee&&l.value!==Jr?Promise.resolve():new Promise((W,ae)=>{te.add([W,ae])})}function be(W){return ee||(ee=!W,X(),te.list().forEach(([ae,ue])=>W?ue(W):ae()),te.reset()),W}function re(W,ae,ue,le){const{scrollBehavior:Ue}=n;if(!sa||!Ue)return Promise.resolve();const I=!ue&&Jz(gx(W.fullPath,0))||(le||!ue)&&history.state&&history.state.scroll||null;return Ss().then(()=>Ue(W,ae,I)).then(D=>D&&Kz(D)).catch(D=>Q(D,W,ae))}const ye=W=>r.go(W);let Ve;const se=new Set,ge={currentRoute:l,listening:!0,addRoute:d,removeRoute:p,clearRoutes:e.clearRoutes,hasRoute:g,getRoutes:_,resolve:m,options:n,push:v,replace:E,go:ye,back:()=>ye(-1),forward:()=>ye(1),beforeEach:s.add,beforeResolve:o.add,afterEach:a.add,onError:Z.add,isReady:de,install(W){const ae=this;W.component("RouterLink",SV),W.component("RouterView",Gw),W.config.globalProperties.$router=ae,Object.defineProperty(W.config.globalProperties,"$route",{enumerable:!0,get:()=>Ot(l)}),sa&&!Ve&&l.value===Jr&&(Ve=!0,v(r.location).catch(Ue=>{}));const ue={};for(const Ue in Jr)Object.defineProperty(ue,Ue,{get:()=>l.value[Ue],enumerable:!0});W.provide(Gd,ae),W.provide(Hw,iS(ue)),W.provide($g,l);const le=W.unmount;se.add(W),W.unmount=function(){se.delete(W),se.size<1&&(c=Jr,V&&V(),V=null,l.value=Jr,Ve=!1,ee=!1),le()}}};function Me(W){return W.reduce((ae,ue)=>ae.then(()=>x(ue)),Promise.resolve())}return ge}function CV(n,e){const t=[],i=[],r=[],s=Math.max(e.matched.length,n.matched.length);for(let o=0;oRa(c,a))?i.push(a):t.push(a));const l=n.matched[o];l&&(e.matched.find(c=>Ra(c,l))||r.push(l))}return[t,i,r]}function RV(){return En(Gd)}const PV=[{path:"/",name:"/",component:()=>ut(()=>import("./index-0FtS8e47.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,1,2,12,13,14,15])),meta:{layout:"stage",stageTransition:{name:"bubble-wave-out"}}},{path:"/:all(.*)",name:"/[...all]",component:()=>ut(()=>import("./_...all_-CfLFDWc0.js"),[])},{path:"/audio",name:"/audio",component:()=>ut(()=>import("./audio-DinYnl_N.js"),[])},{path:"/devtools",children:[{path:"image",name:"/devtools/image",component:()=>ut(()=>import("./image-B7AzUr5g.js"),__vite__mapDeps([16,17]))}]},{path:"/queue",name:"/queue",component:()=>ut(()=>import("./queue-CdKSGkpu.js"),__vite__mapDeps([18,7]))},{path:"/settings",children:[{path:"",name:"/settings/",component:()=>ut(()=>import("./index-BNrxdvv8.js"),__vite__mapDeps([19,4,20,14,21])),meta:{stageTransition:{name:"slide"}}},{path:"appearance",children:[{path:"",name:"/settings/appearance/",component:()=>ut(()=>import("./index-DEIl8OlI.js"),__vite__mapDeps([22,20,4,23,11,10,24,14,25])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"memory",children:[{path:"",name:"/settings/memory/",component:()=>ut(()=>import("./index-B3RGLDyQ.js"),[])}]},{path:"models",children:[{path:"",name:"/settings/models/",component:()=>ut(()=>import("./index-Du8ix7FM.js"),__vite__mapDeps([26,20,9,4,23,11,10,24,14,27])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"modules",children:[{path:"",name:"/settings/modules/",component:()=>ut(()=>import("./index-zxlyBIy_.js"),__vite__mapDeps([28,4,29,30,20,24,14])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"consciousness",name:"/settings/modules/consciousness",component:()=>ut(()=>import("./consciousness-B3RqLnFs.js"),__vite__mapDeps([31,32,10,33,34,4,12,6,14])),meta:{stageTransition:{name:"slide"}}},{path:"memory-long-term",name:"/settings/modules/memory-long-term",component:()=>ut(()=>import("./memory-long-term-BUwL0WhE.js"),[])},{path:"memory-short-term",name:"/settings/modules/memory-short-term",component:()=>ut(()=>import("./memory-short-term-C2rRGrUR.js"),[])},{path:"speech",name:"/settings/modules/speech",component:()=>ut(()=>import("./speech-BAXAx1sa.js"),__vite__mapDeps([35,36,37,38,33,32,10,34,4,6,5,14,39])),meta:{stageTransition:{name:"slide"}}}]},{path:"providers",children:[{path:"",name:"/settings/providers/",component:()=>ut(()=>import("./index-d-t5NO1c.js"),__vite__mapDeps([40,20,4,6,29,30,24,14])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"cloudflare-workers-ai",name:"/settings/providers/cloudflare-workers-ai",component:()=>ut(()=>import("./cloudflare-workers-ai-DW44wYmt.js"),__vite__mapDeps([41,4,6,38,33,42,43,44]))},{path:"deepseek",name:"/settings/providers/deepseek",component:()=>ut(()=>import("./deepseek-C0RKjeMo.js"),__vite__mapDeps([45,4,6,46,11,10,38,33,42,43,44]))},{path:"elevenlabs",name:"/settings/providers/elevenlabs",component:()=>ut(()=>import("./elevenlabs-BwDmvV0f.js"),__vite__mapDeps([47,4,6,5,48,36,37,46,11,10,38,33,42,43]))},{path:"fireworks-ai",name:"/settings/providers/fireworks-ai",component:()=>ut(()=>import("./fireworks-ai-DLDw3hxW.js"),__vite__mapDeps([49,4,6,46,11,10,38,33,42,43,44]))},{path:"microsoft-speech",name:"/settings/providers/microsoft-speech",component:()=>ut(()=>import("./microsoft-speech-CbKBRvT-.js"),__vite__mapDeps([50,38,33,4,6,5,48,36,37,46,11,10,42,43]))},{path:"mistral-ai",name:"/settings/providers/mistral-ai",component:()=>ut(()=>import("./mistral-ai-BSvPWWKn.js"),__vite__mapDeps([51,4,6,46,11,10,38,33,42,43,44]))},{path:"moonshot-ai",name:"/settings/providers/moonshot-ai",component:()=>ut(()=>import("./moonshot-ai-BpNd7lqk.js"),__vite__mapDeps([52,4,6,46,11,10,38,33,42,43,44]))},{path:"novita-ai",name:"/settings/providers/novita-ai",component:()=>ut(()=>import("./novita-ai-CMr47yM2.js"),__vite__mapDeps([53,4,6,46,11,10,38,33,42,43,44]))},{path:"ollama",name:"/settings/providers/ollama",component:()=>ut(()=>import("./ollama-CxlTq2Yg.js"),__vite__mapDeps([54,33,4,6,46,11,10,38,43,44]))},{path:"openai",name:"/settings/providers/openai",component:()=>ut(()=>import("./openai-aA-L1GVd.js"),__vite__mapDeps([55,4,6,46,11,10,38,33,42,43,44]))},{path:"openrouter-ai",name:"/settings/providers/openrouter-ai",component:()=>ut(()=>import("./openrouter-ai-DCnIiw2z.js"),__vite__mapDeps([56,4,6,46,11,10,38,33,42,43,44]))},{path:"together-ai",name:"/settings/providers/together-ai",component:()=>ut(()=>import("./together-ai-DTW1P193.js"),__vite__mapDeps([57,4,6,46,11,10,38,33,42,43,44]))},{path:"xai",name:"/settings/providers/xai",component:()=>ut(()=>import("./xai-CcYrpCYf.js"),__vite__mapDeps([58,4,6,46,11,10,38,33,42,43,44]))}]}]},{path:"/test",children:[{path:"filter-message",name:"/test/filter-message",component:()=>ut(()=>import("./filter-message-Q-pfq8ka.js"),[])},{path:"queues",children:[{path:"delays",name:"/test/queues/delays",component:()=>ut(()=>import("./delays-BG_vAngQ.js"),__vite__mapDeps([59,8,4,7,13]))},{path:"emotions",name:"/test/queues/emotions",component:()=>ut(()=>import("./emotions-cpITk8zy.js"),__vite__mapDeps([60,8,4,7]))},{path:"messages",name:"/test/queues/messages",component:()=>ut(()=>import("./messages-CYVaGXcj.js"),__vite__mapDeps([61,8,4,7]))}]}]}],Ww=(n,e)=>{if(typeof n=="number"){if(e===3)return{mode:"rgb",r:(n>>8&15|n>>4&240)/255,g:(n>>4&15|n&240)/255,b:(n&15|n<<4&240)/255};if(e===4)return{mode:"rgb",r:(n>>12&15|n>>8&240)/255,g:(n>>8&15|n>>4&240)/255,b:(n>>4&15|n&240)/255,alpha:(n&15|n<<4&240)/255};if(e===6)return{mode:"rgb",r:(n>>16&255)/255,g:(n>>8&255)/255,b:(n&255)/255};if(e===8)return{mode:"rgb",r:(n>>24&255)/255,g:(n>>16&255)/255,b:(n>>8&255)/255,alpha:(n&255)/255}}},IV={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},LV=n=>Ww(IV[n.toLowerCase()],6),DV=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,OV=n=>{let e;return(e=n.match(DV))?Ww(parseInt(e[1],16),e[1].length):void 0},hs="([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)",Vl=`${hs}%`,z_=`(?:${hs}%|${hs})`,NV=`(?:${hs}(deg|grad|rad|turn)|${hs})`,Ia="\\s*,\\s*",UV=new RegExp(`^rgba?\\(\\s*${hs}${Ia}${hs}${Ia}${hs}\\s*(?:,\\s*${z_}\\s*)?\\)$`),FV=new RegExp(`^rgba?\\(\\s*${Vl}${Ia}${Vl}${Ia}${Vl}\\s*(?:,\\s*${z_}\\s*)?\\)$`),kV=n=>{let e={mode:"rgb"},t;if(t=n.match(UV))t[1]!==void 0&&(e.r=t[1]/255),t[2]!==void 0&&(e.g=t[2]/255),t[3]!==void 0&&(e.b=t[3]/255);else if(t=n.match(FV))t[1]!==void 0&&(e.r=t[1]/100),t[2]!==void 0&&(e.g=t[2]/100),t[3]!==void 0&&(e.b=t[3]/100);else return;return t[4]!==void 0?e.alpha=Math.max(0,Math.min(1,t[4]/100)):t[5]!==void 0&&(e.alpha=Math.max(0,Math.min(1,+t[5]))),e},BV=(n,e)=>n===void 0?void 0:typeof n!="object"?jV(n):n.mode!==void 0?n:e?{...n,mode:e}:void 0,Xw=(n="rgb")=>e=>(e=BV(e,n))!==void 0?e.mode===n?e:Yi[e.mode][n]?Yi[e.mode][n](e):n==="rgb"?Yi[e.mode].rgb(e):Yi.rgb[n](Yi[e.mode].rgb(e)):void 0,Yi={},$w={},Ih=[],qw={},zV=n=>n,Et=n=>(Yi[n.mode]={...Yi[n.mode],...n.toMode},Object.keys(n.fromMode||{}).forEach(e=>{Yi[e]||(Yi[e]={}),Yi[e][n.mode]=n.fromMode[e]}),n.ranges||(n.ranges={}),n.difference||(n.difference={}),n.channels.forEach(e=>{if(n.ranges[e]===void 0&&(n.ranges[e]=[0,1]),!n.interpolate[e])throw new Error(`Missing interpolator for: ${e}`);typeof n.interpolate[e]=="function"&&(n.interpolate[e]={use:n.interpolate[e]}),n.interpolate[e].fixup||(n.interpolate[e].fixup=zV)}),$w[n.mode]=n,(n.parse||[]).forEach(e=>{HV(e,n.mode)}),Xw(n.mode)),VV=n=>$w[n],HV=(n,e)=>{if(typeof n=="string"){if(!e)throw new Error("'mode' required when 'parser' is a string");qw[n]=e}else typeof n=="function"&&Ih.indexOf(n)<0&&Ih.push(n)},qg=/[^\x00-\x7F]|[a-zA-Z_]/,GV=/[^\x00-\x7F]|[-\w]/,ve={Function:"function",Ident:"ident",Number:"number",Percentage:"percentage",ParenClose:")",None:"none",Hue:"hue",Alpha:"alpha"};let $e=0;function cf(n){let e=n[$e],t=n[$e+1];return e==="-"||e==="+"?/\d/.test(t)||t==="."&&/\d/.test(n[$e+2]):e==="."?/\d/.test(t):/\d/.test(e)}function Yg(n){if($e>=n.length)return!1;let e=n[$e];if(qg.test(e))return!0;if(e==="-"){if(n.length-$e<2)return!1;let t=n[$e+1];return!!(t==="-"||qg.test(t))}return!1}const WV={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function ul(n){let e="";if((n[$e]==="-"||n[$e]==="+")&&(e+=n[$e++]),e+=uf(n),n[$e]==="."&&/\d/.test(n[$e+1])&&(e+=n[$e++]+uf(n)),(n[$e]==="e"||n[$e]==="E")&&((n[$e+1]==="-"||n[$e+1]==="+")&&/\d/.test(n[$e+2])?e+=n[$e++]+n[$e++]+uf(n):/\d/.test(n[$e+1])&&(e+=n[$e++]+uf(n))),Yg(n)){let t=Lh(n);return t==="deg"||t==="rad"||t==="turn"||t==="grad"?{type:ve.Hue,value:e*WV[t]}:void 0}return n[$e]==="%"?($e++,{type:ve.Percentage,value:+e}):{type:ve.Number,value:+e}}function uf(n){let e="";for(;/\d/.test(n[$e]);)e+=n[$e++];return e}function Lh(n){let e="";for(;$e{},ki=Array.isArray,Iw=/#/g,Az=/&/g,Cz=/\//g,Rz=/=/g,Pz=/\?/g,Lw=/\+/g,Iz=/%5B/g,Lz=/%5D/g,Dw=/%5E/g,Dz=/%60/g,Ow=/%7B/g,Oz=/%7C/g,Nw=/%7D/g,Nz=/%20/g;function B_(n){return encodeURI(""+n).replace(Oz,"|").replace(Iz,"[").replace(Lz,"]")}function Uz(n){return B_(n).replace(Ow,"{").replace(Nw,"}").replace(Dw,"^")}function Wg(n){return B_(n).replace(Lw,"%2B").replace(Nz,"+").replace(Iw,"%23").replace(Az,"%26").replace(Dz,"`").replace(Ow,"{").replace(Nw,"}").replace(Dw,"^")}function Fz(n){return Wg(n).replace(Rz,"%3D")}function kz(n){return B_(n).replace(Iw,"%23").replace(Pz,"%3F")}function Bz(n){return n==null?"":kz(n).replace(Cz,"%2F")}function bc(n){try{return decodeURIComponent(""+n)}catch{}return""+n}const zz=/\/$/,Vz=n=>n.replace(zz,"");function ym(n,e,t="/"){let i,r={},s="",o="";const a=e.indexOf("#");let l=e.indexOf("?");return a=0&&(l=-1),l>-1&&(i=e.slice(0,l),s=e.slice(l+1,a>-1?a:e.length),r=n(s)),a>-1&&(i=i||e.slice(0,a),o=e.slice(a,e.length)),i=Xz(i??e,t),{fullPath:i+(s&&"?")+s+o,path:i,query:r,hash:bc(o)}}function Hz(n,e){const t=e.query?n(e.query):"";return e.path+(t&&"?")+t+(e.hash||"")}function px(n,e){return!e||!n.toLowerCase().startsWith(e.toLowerCase())?n:n.slice(e.length)||"/"}function Gz(n,e,t){const i=e.matched.length-1,r=t.matched.length-1;return i>-1&&i===r&&Ra(e.matched[i],t.matched[r])&&Uw(e.params,t.params)&&n(e.query)===n(t.query)&&e.hash===t.hash}function Ra(n,e){return(n.aliasOf||n)===(e.aliasOf||e)}function Uw(n,e){if(Object.keys(n).length!==Object.keys(e).length)return!1;for(const t in n)if(!Wz(n[t],e[t]))return!1;return!0}function Wz(n,e){return ki(n)?mx(n,e):ki(e)?mx(e,n):n===e}function mx(n,e){return ki(e)?n.length===e.length&&n.every((t,i)=>t===e[i]):n.length===1&&n[0]===e}function Xz(n,e){if(n.startsWith("/"))return n;if(!n)return e;const t=e.split("/"),i=n.split("/"),r=i[i.length-1];(r===".."||r===".")&&i.push("");let s=t.length-1,o,a;for(o=0;o1&&s--;else break;return t.slice(0,s).join("/")+"/"+i.slice(o).join("/")}const Jr={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0};var xc;(function(n){n.pop="pop",n.push="push"})(xc||(xc={}));var zl;(function(n){n.back="back",n.forward="forward",n.unknown=""})(zl||(zl={}));function $z(n){if(!n)if(sa){const e=document.querySelector("base");n=e&&e.getAttribute("href")||"/",n=n.replace(/^\w+:\/\/[^\/]+/,"")}else n="/";return n[0]!=="/"&&n[0]!=="#"&&(n="/"+n),Vz(n)}const qz=/^[^#]+#/;function Yz(n,e){return n.replace(qz,"#")+e}function jz(n,e){const t=document.documentElement.getBoundingClientRect(),i=n.getBoundingClientRect();return{behavior:e.behavior,left:i.left-t.left-(e.left||0),top:i.top-t.top-(e.top||0)}}const Hd=()=>({left:window.scrollX,top:window.scrollY});function Kz(n){let e;if("el"in n){const t=n.el,i=typeof t=="string"&&t.startsWith("#"),r=typeof t=="string"?i?document.getElementById(t.slice(1)):document.querySelector(t):t;if(!r)return;e=jz(r,n)}else e=n;"scrollBehavior"in document.documentElement.style?window.scrollTo(e):window.scrollTo(e.left!=null?e.left:window.scrollX,e.top!=null?e.top:window.scrollY)}function gx(n,e){return(history.state?history.state.position-e:-1)+n}const Xg=new Map;function Zz(n,e){Xg.set(n,e)}function Jz(n){const e=Xg.get(n);return Xg.delete(n),e}let Qz=()=>location.protocol+"//"+location.host;function Fw(n,e){const{pathname:t,search:i,hash:r}=e,s=n.indexOf("#");if(s>-1){let a=r.includes(n.slice(s))?n.slice(s).length:1,l=r.slice(a);return l[0]!=="/"&&(l="/"+l),px(l,"")}return px(t,n)+i+r}function eV(n,e,t,i){let r=[],s=[],o=null;const a=({state:h})=>{const d=Fw(n,location),p=t.value,_=e.value;let g=0;if(h){if(t.value=d,e.value=h,o&&o===p){o=null;return}g=_?h.position-_.position:0}else i(d);r.forEach(m=>{m(t.value,p,{delta:g,type:xc.pop,direction:g?g>0?zl.forward:zl.back:zl.unknown})})};function l(){o=t.value}function c(h){r.push(h);const d=()=>{const p=r.indexOf(h);p>-1&&r.splice(p,1)};return s.push(d),d}function u(){const{history:h}=window;h.state&&h.replaceState(Mt({},h.state,{scroll:Hd()}),"")}function f(){for(const h of s)h();s=[],window.removeEventListener("popstate",a),window.removeEventListener("beforeunload",u)}return window.addEventListener("popstate",a),window.addEventListener("beforeunload",u,{passive:!0}),{pauseListeners:l,listen:c,destroy:f}}function _x(n,e,t,i=!1,r=!1){return{back:n,current:e,forward:t,replaced:i,position:window.history.length,scroll:r?Hd():null}}function tV(n){const{history:e,location:t}=window,i={value:Fw(n,t)},r={value:e.state};r.value||s(i.value,{back:null,current:i.value,forward:null,position:e.length-1,replaced:!0,scroll:null},!0);function s(l,c,u){const f=n.indexOf("#"),h=f>-1?(t.host&&document.querySelector("base")?n:n.slice(f))+l:Qz()+n+l;try{e[u?"replaceState":"pushState"](c,"",h),r.value=c}catch(d){console.error(d),t[u?"replace":"assign"](h)}}function o(l,c){const u=Mt({},e.state,_x(r.value.back,l,r.value.forward,!0),c,{position:r.value.position});s(l,u,!0),i.value=l}function a(l,c){const u=Mt({},r.value,e.state,{forward:l,scroll:Hd()});s(u.current,u,!0);const f=Mt({},_x(i.value,l,null),{position:u.position+1},c);s(l,f,!1),i.value=l}return{location:i,state:r,push:a,replace:o}}function nV(n){n=$z(n);const e=tV(n),t=eV(n,e.state,e.location,e.replace);function i(s,o=!0){o||t.pauseListeners(),history.go(s)}const r=Mt({location:"",base:n,go:i,createHref:Yz.bind(null,n)},e,t);return Object.defineProperty(r,"location",{enumerable:!0,get:()=>e.location.value}),Object.defineProperty(r,"state",{enumerable:!0,get:()=>e.state.value}),r}function iV(n){return n=location.host?n||location.pathname+location.search:"",n.includes("#")||(n+="#"),nV(n)}function rV(n){return typeof n=="string"||n&&typeof n=="object"}function kw(n){return typeof n=="string"||typeof n=="symbol"}const Bw=Symbol("");var vx;(function(n){n[n.aborted=4]="aborted",n[n.cancelled=8]="cancelled",n[n.duplicated=16]="duplicated"})(vx||(vx={}));function Pa(n,e){return Mt(new Error,{type:n,[Bw]:!0},e)}function gr(n,e){return n instanceof Error&&Bw in n&&(e==null||!!(n.type&e))}const yx="[^/]+?",sV={sensitive:!1,strict:!1,start:!0,end:!0},oV=/[.+*?^${}()[\]/\\]/g;function aV(n,e){const t=Mt({},sV,e),i=[];let r=t.start?"^":"";const s=[];for(const c of n){const u=c.length?[]:[90];t.strict&&!c.length&&(r+="/");for(let f=0;fe.length?e.length===1&&e[0]===80?1:-1:0}function zw(n,e){let t=0;const i=n.score,r=e.score;for(;t0&&e[e.length-1]<0}const cV={type:0,value:""},uV=/[a-zA-Z0-9_]/;function fV(n){if(!n)return[[]];if(n==="/")return[[cV]];if(!n.startsWith("/"))throw new Error(`Invalid path "${n}"`);function e(d){throw new Error(`ERR (${t})/"${c}": ${d}`)}let t=0,i=t;const r=[];let s;function o(){s&&r.push(s),s=[]}let a=0,l,c="",u="";function f(){c&&(t===0?s.push({type:0,value:c}):t===1||t===2||t===3?(s.length>1&&(l==="*"||l==="+")&&e(`A repeatable param (${c}) must be alone in its segment. eg: '/:ids+.`),s.push({type:1,value:c,regexp:u,repeatable:l==="*"||l==="+",optional:l==="*"||l==="?"})):e("Invalid state to consume buffer"),c="")}function h(){c+=l}for(;a{o(b)}:Bl}function o(f){if(kw(f)){const h=i.get(f);h&&(i.delete(f),t.splice(t.indexOf(h),1),h.children.forEach(o),h.alias.forEach(o))}else{const h=t.indexOf(f);h>-1&&(t.splice(h,1),f.record.name&&i.delete(f.record.name),f.children.forEach(o),f.alias.forEach(o))}}function a(){return t}function l(f){const h=gV(f,t);t.splice(h,0,f),f.record.name&&!Sx(f)&&i.set(f.record.name,f)}function c(f,h){let d,p={},_,g;if("name"in f&&f.name){if(d=i.get(f.name),!d)throw Pa(1,{location:f});g=d.record.name,p=Mt(xx(h.params,d.keys.filter(b=>!b.optional).concat(d.parent?d.parent.keys.filter(b=>b.optional):[]).map(b=>b.name)),f.params&&xx(f.params,d.keys.map(b=>b.name))),_=d.stringify(p)}else if(f.path!=null)_=f.path,d=t.find(b=>b.re.test(_)),d&&(p=d.parse(_),g=d.record.name);else{if(d=h.name?i.get(h.name):t.find(b=>b.re.test(h.path)),!d)throw Pa(1,{location:f,currentLocation:h});g=d.record.name,p=Mt({},h.params,f.params),_=d.stringify(p)}const m=[];let y=d;for(;y;)m.unshift(y.record),y=y.parent;return{name:g,path:_,params:p,matched:m,meta:mV(m)}}n.forEach(f=>s(f));function u(){t.length=0,i.clear()}return{addRoute:s,resolve:c,removeRoute:o,clearRoutes:u,getRoutes:a,getRecordMatcher:r}}function xx(n,e){const t={};for(const i of e)i in n&&(t[i]=n[i]);return t}function Mx(n){const e={path:n.path,redirect:n.redirect,name:n.name,meta:n.meta||{},aliasOf:n.aliasOf,beforeEnter:n.beforeEnter,props:pV(n),children:n.children||[],instances:{},leaveGuards:new Set,updateGuards:new Set,enterCallbacks:{},components:"components"in n?n.components||null:n.component&&{default:n.component}};return Object.defineProperty(e,"mods",{value:{}}),e}function pV(n){const e={},t=n.props||!1;if("component"in n)e.default=t;else for(const i in n.components)e[i]=typeof t=="object"?t[i]:t;return e}function Sx(n){for(;n;){if(n.record.aliasOf)return!0;n=n.parent}return!1}function mV(n){return n.reduce((e,t)=>Mt(e,t.meta),{})}function Ex(n,e){const t={};for(const i in n)t[i]=i in e?e[i]:n[i];return t}function gV(n,e){let t=0,i=e.length;for(;t!==i;){const s=t+i>>1;zw(n,e[s])<0?i=s:t=s+1}const r=_V(n);return r&&(i=e.lastIndexOf(r,i-1)),i}function _V(n){let e=n;for(;e=e.parent;)if(Vw(e)&&zw(n,e)===0)return e}function Vw({record:n}){return!!(n.name||n.components&&Object.keys(n.components).length||n.redirect)}function vV(n){const e={};if(n===""||n==="?")return e;const i=(n[0]==="?"?n.slice(1):n).split("&");for(let r=0;rs&&Wg(s)):[i&&Wg(i)]).forEach(s=>{s!==void 0&&(e+=(e.length?"&":"")+t,s!=null&&(e+="="+s))})}return e}function yV(n){const e={};for(const t in n){const i=n[t];i!==void 0&&(e[t]=ki(i)?i.map(r=>r==null?null:""+r):i==null?i:""+i)}return e}const bV=Symbol(""),wx=Symbol(""),Gd=Symbol(""),Hw=Symbol(""),$g=Symbol("");function cl(){let n=[];function e(i){return n.push(i),()=>{const r=n.indexOf(i);r>-1&&n.splice(r,1)}}function t(){n=[]}return{add:e,list:()=>n.slice(),reset:t}}function os(n,e,t,i,r,s=o=>o()){const o=i&&(i.enterCallbacks[r]=i.enterCallbacks[r]||[]);return()=>new Promise((a,l)=>{const c=h=>{h===!1?l(Pa(4,{from:t,to:e})):h instanceof Error?l(h):rV(h)?l(Pa(2,{from:e,to:h})):(o&&i.enterCallbacks[r]===o&&typeof h=="function"&&o.push(h),a())},u=s(()=>n.call(i&&i.instances[r],e,t,c));let f=Promise.resolve(u);n.length<3&&(f=f.then(c)),f.catch(h=>l(h))})}function bm(n,e,t,i,r=s=>s()){const s=[];for(const o of n)for(const a in o.components){let l=o.components[a];if(!(e!=="beforeRouteEnter"&&!o.instances[a]))if(Pw(l)){const u=(l.__vccOpts||l)[e];u&&s.push(os(u,t,i,o,a,r))}else{let c=l();s.push(()=>c.then(u=>{if(!u)throw new Error(`Couldn't resolve component "${a}" at "${o.path}"`);const f=wz(u)?u.default:u;o.mods[a]=u,o.components[a]=f;const d=(f.__vccOpts||f)[e];return d&&os(d,t,i,o,a,r)()}))}}return s}function Ax(n){const e=En(Gd),t=En(Hw),i=Se(()=>{const l=Ot(n.to);return e.resolve(l)}),r=Se(()=>{const{matched:l}=i.value,{length:c}=l,u=l[c-1],f=t.matched;if(!u||!f.length)return-1;const h=f.findIndex(Ra.bind(null,u));if(h>-1)return h;const d=Cx(l[c-2]);return c>1&&Cx(u)===d&&f[f.length-1].path!==d?f.findIndex(Ra.bind(null,l[c-2])):h}),s=Se(()=>r.value>-1&&TV(t.params,i.value.params)),o=Se(()=>r.value>-1&&r.value===t.matched.length-1&&Uw(t.params,i.value.params));function a(l={}){if(EV(l)){const c=e[Ot(n.replace)?"replace":"push"](Ot(n.to)).catch(Bl);return n.viewTransition&&typeof document<"u"&&"startViewTransition"in document&&document.startViewTransition(()=>c),c}return Promise.resolve()}return{route:i,href:Se(()=>i.value.href),isActive:s,isExactActive:o,navigate:a}}function xV(n){return n.length===1?n[0]:n}const MV=fn({name:"RouterLink",compatConfig:{MODE:3},props:{to:{type:[String,Object],required:!0},replace:Boolean,activeClass:String,exactActiveClass:String,custom:Boolean,ariaCurrentValue:{type:String,default:"page"}},useLink:Ax,setup(n,{slots:e}){const t=bi(Ax(n)),{options:i}=En(Gd),r=Se(()=>({[Rx(n.activeClass,i.linkActiveClass,"router-link-active")]:t.isActive,[Rx(n.exactActiveClass,i.linkExactActiveClass,"router-link-exact-active")]:t.isExactActive}));return()=>{const s=e.default&&xV(e.default(t));return n.custom?s:Lr("a",{"aria-current":t.isExactActive?n.ariaCurrentValue:null,href:t.href,onClick:t.navigate,class:r.value},s)}}}),SV=MV;function EV(n){if(!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)&&!n.defaultPrevented&&!(n.button!==void 0&&n.button!==0)){if(n.currentTarget&&n.currentTarget.getAttribute){const e=n.currentTarget.getAttribute("target");if(/\b_blank\b/i.test(e))return}return n.preventDefault&&n.preventDefault(),!0}}function TV(n,e){for(const t in e){const i=e[t],r=n[t];if(typeof i=="string"){if(i!==r)return!1}else if(!ki(r)||r.length!==i.length||i.some((s,o)=>s!==r[o]))return!1}return!0}function Cx(n){return n?n.aliasOf?n.aliasOf.path:n.path:""}const Rx=(n,e,t)=>n??e??t,wV=fn({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(n,{attrs:e,slots:t}){const i=En($g),r=Se(()=>n.route||i.value),s=En(wx,0),o=Se(()=>{let c=Ot(s);const{matched:u}=r.value;let f;for(;(f=u[c])&&!f.components;)c++;return c}),a=Se(()=>r.value.matched[o.value]);fs(wx,Se(()=>o.value+1)),fs(bV,a),fs($g,r);const l=et();return Xe(()=>[l.value,a.value,n.name],([c,u,f],[h,d,p])=>{u&&(u.instances[f]=c,d&&d!==u&&c&&c===h&&(u.leaveGuards.size||(u.leaveGuards=d.leaveGuards),u.updateGuards.size||(u.updateGuards=d.updateGuards))),c&&u&&(!d||!Ra(u,d)||!h)&&(u.enterCallbacks[f]||[]).forEach(_=>_(c))},{flush:"post"}),()=>{const c=r.value,u=n.name,f=a.value,h=f&&f.components[u];if(!h)return Px(t.default,{Component:h,route:c});const d=f.props[u],p=d?d===!0?c.params:typeof d=="function"?d(c):d:null,g=Lr(h,Mt({},p,e,{onVnodeUnmounted:m=>{m.component.isUnmounted&&(f.instances[u]=null)},ref:l}));return Px(t.default,{Component:g,route:c})||g}}});function Px(n,e){if(!n)return null;const t=n(e);return t.length===1?t[0]:t}const Gw=wV;function AV(n){const e=dV(n.routes,n),t=n.parseQuery||vV,i=n.stringifyQuery||Tx,r=n.history,s=cl(),o=cl(),a=cl(),l=De(Jr);let c=Jr;sa&&n.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const u=vm.bind(null,W=>""+W),f=vm.bind(null,Bz),h=vm.bind(null,bc);function d(W,ae){let ue,le;return kw(W)?(ue=e.getRecordMatcher(W),le=ae):le=W,e.addRoute(le,ue)}function p(W){const ae=e.getRecordMatcher(W);ae&&e.removeRoute(ae)}function _(){return e.getRoutes().map(W=>W.record)}function g(W){return!!e.getRecordMatcher(W)}function m(W,ae){if(ae=Mt({},ae||l.value),typeof W=="string"){const w=ym(t,W,ae.path),j=e.resolve({path:w.path},ae),G=r.createHref(w.fullPath);return Mt(w,j,{params:h(j.params),hash:bc(w.hash),redirectedFrom:void 0,href:G})}let ue;if(W.path!=null)ue=Mt({},W,{path:ym(t,W.path,ae.path).path});else{const w=Mt({},W.params);for(const j in w)w[j]==null&&delete w[j];ue=Mt({},W,{params:f(w)}),ae.params=f(ae.params)}const le=e.resolve(ue,ae),Ue=W.hash||"";le.params=u(h(le.params));const I=Hz(i,Mt({},W,{hash:Uz(Ue),path:le.path})),D=r.createHref(I);return Mt({fullPath:I,hash:Ue,query:i===Tx?yV(W.query):W.query||{}},le,{redirectedFrom:void 0,href:D})}function y(W){return typeof W=="string"?ym(t,W,l.value.path):Mt({},W)}function b(W,ae){if(c!==W)return Pa(8,{from:ae,to:W})}function v(W){return S(W)}function E(W){return v(Mt(y(W),{replace:!0}))}function T(W){const ae=W.matched[W.matched.length-1];if(ae&&ae.redirect){const{redirect:ue}=ae;let le=typeof ue=="function"?ue(W):ue;return typeof le=="string"&&(le=le.includes("?")||le.includes("#")?le=y(le):{path:le},le.params={}),Mt({query:W.query,hash:W.hash,params:le.path!=null?{}:W.params},le)}}function S(W,ae){const ue=c=m(W),le=l.value,Ue=W.state,I=W.force,D=W.replace===!0,w=T(ue);if(w)return S(Mt(y(w),{state:typeof w=="object"?Mt({},Ue,w.state):Ue,force:I,replace:D}),ae||ue);const j=ue;j.redirectedFrom=ae;let G;return!I&&Gz(i,le,ue)&&(G=Pa(16,{to:j,from:le}),re(le,le,!0,!1)),(G?Promise.resolve(G):M(j,le)).catch(q=>gr(q)?gr(q,2)?q:be(q):Q(q,j,le)).then(q=>{if(q){if(gr(q,2))return S(Mt({replace:D},y(q.to),{state:typeof q.to=="object"?Mt({},Ue,q.to.state):Ue,force:I}),ae||j)}else q=F(j,le,!0,D,Ue);return L(j,le,q),q})}function R(W,ae){const ue=b(W,ae);return ue?Promise.reject(ue):Promise.resolve()}function x(W){const ae=se.values().next().value;return ae&&typeof ae.runWithContext=="function"?ae.runWithContext(W):W()}function M(W,ae){let ue;const[le,Ue,I]=CV(W,ae);ue=bm(le.reverse(),"beforeRouteLeave",W,ae);for(const w of le)w.leaveGuards.forEach(j=>{ue.push(os(j,W,ae))});const D=R.bind(null,W,ae);return ue.push(D),Me(ue).then(()=>{ue=[];for(const w of s.list())ue.push(os(w,W,ae));return ue.push(D),Me(ue)}).then(()=>{ue=bm(Ue,"beforeRouteUpdate",W,ae);for(const w of Ue)w.updateGuards.forEach(j=>{ue.push(os(j,W,ae))});return ue.push(D),Me(ue)}).then(()=>{ue=[];for(const w of I)if(w.beforeEnter)if(ki(w.beforeEnter))for(const j of w.beforeEnter)ue.push(os(j,W,ae));else ue.push(os(w.beforeEnter,W,ae));return ue.push(D),Me(ue)}).then(()=>(W.matched.forEach(w=>w.enterCallbacks={}),ue=bm(I,"beforeRouteEnter",W,ae,x),ue.push(D),Me(ue))).then(()=>{ue=[];for(const w of o.list())ue.push(os(w,W,ae));return ue.push(D),Me(ue)}).catch(w=>gr(w,8)?w:Promise.reject(w))}function L(W,ae,ue){a.list().forEach(le=>x(()=>le(W,ae,ue)))}function F(W,ae,ue,le,Ue){const I=b(W,ae);if(I)return I;const D=ae===Jr,w=sa?history.state:{};ue&&(le||D?r.replace(W.fullPath,Mt({scroll:D&&w&&w.scroll},Ue)):r.push(W.fullPath,Ue)),l.value=W,re(W,ae,ue,D),be()}let V;function X(){V||(V=r.listen((W,ae,ue)=>{if(!ge.listening)return;const le=m(W),Ue=T(le);if(Ue){S(Mt(Ue,{replace:!0,force:!0}),le).catch(Bl);return}c=le;const I=l.value;sa&&Zz(gx(I.fullPath,ue.delta),Hd()),M(le,I).catch(D=>gr(D,12)?D:gr(D,2)?(S(Mt(y(D.to),{force:!0}),le).then(w=>{gr(w,20)&&!ue.delta&&ue.type===xc.pop&&r.go(-1,!1)}).catch(Bl),Promise.reject()):(ue.delta&&r.go(-ue.delta,!1),Q(D,le,I))).then(D=>{D=D||F(le,I,!1),D&&(ue.delta&&!gr(D,8)?r.go(-ue.delta,!1):ue.type===xc.pop&&gr(D,20)&&r.go(-1,!1)),L(le,I,D)}).catch(Bl)}))}let te=cl(),Z=cl(),ee;function Q(W,ae,ue){be(W);const le=Z.list();return le.length?le.forEach(Ue=>Ue(W,ae,ue)):console.error(W),Promise.reject(W)}function de(){return ee&&l.value!==Jr?Promise.resolve():new Promise((W,ae)=>{te.add([W,ae])})}function be(W){return ee||(ee=!W,X(),te.list().forEach(([ae,ue])=>W?ue(W):ae()),te.reset()),W}function re(W,ae,ue,le){const{scrollBehavior:Ue}=n;if(!sa||!Ue)return Promise.resolve();const I=!ue&&Jz(gx(W.fullPath,0))||(le||!ue)&&history.state&&history.state.scroll||null;return Ss().then(()=>Ue(W,ae,I)).then(D=>D&&Kz(D)).catch(D=>Q(D,W,ae))}const ye=W=>r.go(W);let Ve;const se=new Set,ge={currentRoute:l,listening:!0,addRoute:d,removeRoute:p,clearRoutes:e.clearRoutes,hasRoute:g,getRoutes:_,resolve:m,options:n,push:v,replace:E,go:ye,back:()=>ye(-1),forward:()=>ye(1),beforeEach:s.add,beforeResolve:o.add,afterEach:a.add,onError:Z.add,isReady:de,install(W){const ae=this;W.component("RouterLink",SV),W.component("RouterView",Gw),W.config.globalProperties.$router=ae,Object.defineProperty(W.config.globalProperties,"$route",{enumerable:!0,get:()=>Ot(l)}),sa&&!Ve&&l.value===Jr&&(Ve=!0,v(r.location).catch(Ue=>{}));const ue={};for(const Ue in Jr)Object.defineProperty(ue,Ue,{get:()=>l.value[Ue],enumerable:!0});W.provide(Gd,ae),W.provide(Hw,iS(ue)),W.provide($g,l);const le=W.unmount;se.add(W),W.unmount=function(){se.delete(W),se.size<1&&(c=Jr,V&&V(),V=null,l.value=Jr,Ve=!1,ee=!1),le()}}};function Me(W){return W.reduce((ae,ue)=>ae.then(()=>x(ue)),Promise.resolve())}return ge}function CV(n,e){const t=[],i=[],r=[],s=Math.max(e.matched.length,n.matched.length);for(let o=0;oRa(c,a))?i.push(a):t.push(a));const l=n.matched[o];l&&(e.matched.find(c=>Ra(c,l))||r.push(l))}return[t,i,r]}function RV(){return En(Gd)}const PV=[{path:"/",name:"/",component:()=>ut(()=>import("./index-CgcZzzI2.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,1,2,12,13,14,15])),meta:{layout:"stage",stageTransition:{name:"bubble-wave-out"}}},{path:"/:all(.*)",name:"/[...all]",component:()=>ut(()=>import("./_...all_-xa5MzuBe.js"),[])},{path:"/audio",name:"/audio",component:()=>ut(()=>import("./audio-Bsbq-iZ9.js"),[])},{path:"/devtools",children:[{path:"image",name:"/devtools/image",component:()=>ut(()=>import("./image-CD6Zjbv1.js"),__vite__mapDeps([16,17]))}]},{path:"/queue",name:"/queue",component:()=>ut(()=>import("./queue-CHfe46kZ.js"),__vite__mapDeps([18,7]))},{path:"/settings",children:[{path:"",name:"/settings/",component:()=>ut(()=>import("./index-Rz4v4VGO.js"),__vite__mapDeps([19,4,20,14,21])),meta:{stageTransition:{name:"slide"}}},{path:"appearance",children:[{path:"",name:"/settings/appearance/",component:()=>ut(()=>import("./index-ebWEHfej.js"),__vite__mapDeps([22,20,4,23,11,10,24,14,25])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"memory",children:[{path:"",name:"/settings/memory/",component:()=>ut(()=>import("./index-DMp81NbJ.js"),[])}]},{path:"models",children:[{path:"",name:"/settings/models/",component:()=>ut(()=>import("./index-exdkhaXa.js"),__vite__mapDeps([26,20,9,4,23,11,10,24,14,27])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"modules",children:[{path:"",name:"/settings/modules/",component:()=>ut(()=>import("./index-CWukm1n3.js"),__vite__mapDeps([28,4,29,30,20,24,14])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"consciousness",name:"/settings/modules/consciousness",component:()=>ut(()=>import("./consciousness-iz2nv6B3.js"),__vite__mapDeps([31,32,10,33,34,4,12,6,14])),meta:{stageTransition:{name:"slide"}}},{path:"memory-long-term",name:"/settings/modules/memory-long-term",component:()=>ut(()=>import("./memory-long-term-C3e3nLW5.js"),[])},{path:"memory-short-term",name:"/settings/modules/memory-short-term",component:()=>ut(()=>import("./memory-short-term-r0JH0hk6.js"),[])},{path:"speech",name:"/settings/modules/speech",component:()=>ut(()=>import("./speech-BzDSuaZq.js"),__vite__mapDeps([35,36,37,38,33,32,10,34,4,6,5,14,39])),meta:{stageTransition:{name:"slide"}}}]},{path:"providers",children:[{path:"",name:"/settings/providers/",component:()=>ut(()=>import("./index-CTgzm8SA.js"),__vite__mapDeps([40,20,4,6,29,30,24,14])),meta:{stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"cloudflare-workers-ai",name:"/settings/providers/cloudflare-workers-ai",component:()=>ut(()=>import("./cloudflare-workers-ai-DV3XjoGA.js"),__vite__mapDeps([41,4,6,38,33,42,43,44]))},{path:"deepseek",name:"/settings/providers/deepseek",component:()=>ut(()=>import("./deepseek-CjDfnLNQ.js"),__vite__mapDeps([45,4,6,46,11,10,38,33,42,43,44]))},{path:"elevenlabs",name:"/settings/providers/elevenlabs",component:()=>ut(()=>import("./elevenlabs-3ONCU5wo.js"),__vite__mapDeps([47,4,6,5,48,36,37,46,11,10,38,33,42,43]))},{path:"fireworks-ai",name:"/settings/providers/fireworks-ai",component:()=>ut(()=>import("./fireworks-ai-BpaEuc1J.js"),__vite__mapDeps([49,4,6,46,11,10,38,33,42,43,44]))},{path:"microsoft-speech",name:"/settings/providers/microsoft-speech",component:()=>ut(()=>import("./microsoft-speech-BPOz5ZLq.js"),__vite__mapDeps([50,38,33,4,6,5,48,36,37,46,11,10,42,43]))},{path:"mistral-ai",name:"/settings/providers/mistral-ai",component:()=>ut(()=>import("./mistral-ai-C7perH7S.js"),__vite__mapDeps([51,4,6,46,11,10,38,33,42,43,44]))},{path:"moonshot-ai",name:"/settings/providers/moonshot-ai",component:()=>ut(()=>import("./moonshot-ai-CZlBN-5-.js"),__vite__mapDeps([52,4,6,46,11,10,38,33,42,43,44]))},{path:"novita-ai",name:"/settings/providers/novita-ai",component:()=>ut(()=>import("./novita-ai-BTL9go8K.js"),__vite__mapDeps([53,4,6,46,11,10,38,33,42,43,44]))},{path:"ollama",name:"/settings/providers/ollama",component:()=>ut(()=>import("./ollama-qKIKZqA2.js"),__vite__mapDeps([54,33,4,6,46,11,10,38,43,44]))},{path:"openai",name:"/settings/providers/openai",component:()=>ut(()=>import("./openai-BtuP56e_.js"),__vite__mapDeps([55,4,6,46,11,10,38,33,42,43,44]))},{path:"openrouter-ai",name:"/settings/providers/openrouter-ai",component:()=>ut(()=>import("./openrouter-ai-CCt-Li_l.js"),__vite__mapDeps([56,4,6,46,11,10,38,33,42,43,44]))},{path:"together-ai",name:"/settings/providers/together-ai",component:()=>ut(()=>import("./together-ai-BSofzTUT.js"),__vite__mapDeps([57,4,6,46,11,10,38,33,42,43,44]))},{path:"xai",name:"/settings/providers/xai",component:()=>ut(()=>import("./xai-BtPhk-ua.js"),__vite__mapDeps([58,4,6,46,11,10,38,33,42,43,44]))}]}]},{path:"/test",children:[{path:"filter-message",name:"/test/filter-message",component:()=>ut(()=>import("./filter-message-BeLJKrV5.js"),[])},{path:"queues",children:[{path:"delays",name:"/test/queues/delays",component:()=>ut(()=>import("./delays-Cwu4yMJH.js"),__vite__mapDeps([59,8,4,7,13]))},{path:"emotions",name:"/test/queues/emotions",component:()=>ut(()=>import("./emotions-D6mNjsWQ.js"),__vite__mapDeps([60,8,4,7]))},{path:"messages",name:"/test/queues/messages",component:()=>ut(()=>import("./messages-CT9yvwKz.js"),__vite__mapDeps([61,8,4,7]))}]}]}],Ww=(n,e)=>{if(typeof n=="number"){if(e===3)return{mode:"rgb",r:(n>>8&15|n>>4&240)/255,g:(n>>4&15|n&240)/255,b:(n&15|n<<4&240)/255};if(e===4)return{mode:"rgb",r:(n>>12&15|n>>8&240)/255,g:(n>>8&15|n>>4&240)/255,b:(n>>4&15|n&240)/255,alpha:(n&15|n<<4&240)/255};if(e===6)return{mode:"rgb",r:(n>>16&255)/255,g:(n>>8&255)/255,b:(n&255)/255};if(e===8)return{mode:"rgb",r:(n>>24&255)/255,g:(n>>16&255)/255,b:(n>>8&255)/255,alpha:(n&255)/255}}},IV={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},LV=n=>Ww(IV[n.toLowerCase()],6),DV=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,OV=n=>{let e;return(e=n.match(DV))?Ww(parseInt(e[1],16),e[1].length):void 0},hs="([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)",Vl=`${hs}%`,z_=`(?:${hs}%|${hs})`,NV=`(?:${hs}(deg|grad|rad|turn)|${hs})`,Ia="\\s*,\\s*",UV=new RegExp(`^rgba?\\(\\s*${hs}${Ia}${hs}${Ia}${hs}\\s*(?:,\\s*${z_}\\s*)?\\)$`),FV=new RegExp(`^rgba?\\(\\s*${Vl}${Ia}${Vl}${Ia}${Vl}\\s*(?:,\\s*${z_}\\s*)?\\)$`),kV=n=>{let e={mode:"rgb"},t;if(t=n.match(UV))t[1]!==void 0&&(e.r=t[1]/255),t[2]!==void 0&&(e.g=t[2]/255),t[3]!==void 0&&(e.b=t[3]/255);else if(t=n.match(FV))t[1]!==void 0&&(e.r=t[1]/100),t[2]!==void 0&&(e.g=t[2]/100),t[3]!==void 0&&(e.b=t[3]/100);else return;return t[4]!==void 0?e.alpha=Math.max(0,Math.min(1,t[4]/100)):t[5]!==void 0&&(e.alpha=Math.max(0,Math.min(1,+t[5]))),e},BV=(n,e)=>n===void 0?void 0:typeof n!="object"?jV(n):n.mode!==void 0?n:e?{...n,mode:e}:void 0,Xw=(n="rgb")=>e=>(e=BV(e,n))!==void 0?e.mode===n?e:Yi[e.mode][n]?Yi[e.mode][n](e):n==="rgb"?Yi[e.mode].rgb(e):Yi.rgb[n](Yi[e.mode].rgb(e)):void 0,Yi={},$w={},Ih=[],qw={},zV=n=>n,Et=n=>(Yi[n.mode]={...Yi[n.mode],...n.toMode},Object.keys(n.fromMode||{}).forEach(e=>{Yi[e]||(Yi[e]={}),Yi[e][n.mode]=n.fromMode[e]}),n.ranges||(n.ranges={}),n.difference||(n.difference={}),n.channels.forEach(e=>{if(n.ranges[e]===void 0&&(n.ranges[e]=[0,1]),!n.interpolate[e])throw new Error(`Missing interpolator for: ${e}`);typeof n.interpolate[e]=="function"&&(n.interpolate[e]={use:n.interpolate[e]}),n.interpolate[e].fixup||(n.interpolate[e].fixup=zV)}),$w[n.mode]=n,(n.parse||[]).forEach(e=>{HV(e,n.mode)}),Xw(n.mode)),VV=n=>$w[n],HV=(n,e)=>{if(typeof n=="string"){if(!e)throw new Error("'mode' required when 'parser' is a string");qw[n]=e}else typeof n=="function"&&Ih.indexOf(n)<0&&Ih.push(n)},qg=/[^\x00-\x7F]|[a-zA-Z_]/,GV=/[^\x00-\x7F]|[-\w]/,ve={Function:"function",Ident:"ident",Number:"number",Percentage:"percentage",ParenClose:")",None:"none",Hue:"hue",Alpha:"alpha"};let $e=0;function cf(n){let e=n[$e],t=n[$e+1];return e==="-"||e==="+"?/\d/.test(t)||t==="."&&/\d/.test(n[$e+2]):e==="."?/\d/.test(t):/\d/.test(e)}function Yg(n){if($e>=n.length)return!1;let e=n[$e];if(qg.test(e))return!0;if(e==="-"){if(n.length-$e<2)return!1;let t=n[$e+1];return!!(t==="-"||qg.test(t))}return!1}const WV={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function ul(n){let e="";if((n[$e]==="-"||n[$e]==="+")&&(e+=n[$e++]),e+=uf(n),n[$e]==="."&&/\d/.test(n[$e+1])&&(e+=n[$e++]+uf(n)),(n[$e]==="e"||n[$e]==="E")&&((n[$e+1]==="-"||n[$e+1]==="+")&&/\d/.test(n[$e+2])?e+=n[$e++]+n[$e++]+uf(n):/\d/.test(n[$e+1])&&(e+=n[$e++]+uf(n))),Yg(n)){let t=Lh(n);return t==="deg"||t==="rad"||t==="turn"||t==="grad"?{type:ve.Hue,value:e*WV[t]}:void 0}return n[$e]==="%"?($e++,{type:ve.Percentage,value:+e}):{type:ve.Number,value:+e}}function uf(n){let e="";for(;/\d/.test(n[$e]);)e+=n[$e++];return e}function Lh(n){let e="";for(;$e4)){if(t.length===4){if(t[3].type!==ve.Alpha)return;t[3]=t[3].value}return t.length===3&&t.push({type:ve.None,value:void 0}),t.every(r=>r.type!==ve.Alpha)?t:void 0}}function YV(n,e){n._i=0;let t=n[n._i++];if(!t||t.type!==ve.Function)return;let i=Yw(n,e);if(i)return i.unshift(t.value),i}const jV=n=>{if(typeof n!="string")return;const e=$V(n),t=e?YV(e,!0):void 0;let i,r=0,s=Ih.length;for(;rn==="transparent"?{mode:"rgb",r:0,g:0,b:0,alpha:0}:void 0,JV=(n,e,t)=>n+t*(e-n),QV=n=>{let e=[];for(let t=0;te=>{let t=QV(e);return i=>{let r=i*t.length,s=i>=1?t.length-1:Math.max(Math.floor(r),0),o=t[s];return o===void 0?void 0:n(o[0],o[1],r-s)}},we=e6(JV),on=n=>{let e=!1,t=n.map(i=>i!==void 0?(e=!0,i):1);return e?t:n},Ga={mode:"rgb",channels:["r","g","b","alpha"],parse:[KV,OV,kV,LV,ZV,"srgb"],serialize:"srgb",interpolate:{r:we,g:we,b:we,alpha:{use:we,fixup:on}},gamut:!0,white:{r:1,g:1,b:1},black:{r:0,g:0,b:0}},xm=(n=0)=>Math.pow(Math.abs(n),563/256)*Math.sign(n),Ix=n=>{let e=xm(n.r),t=xm(n.g),i=xm(n.b),r={mode:"xyz65",x:.5766690429101305*e+.1855582379065463*t+.1882286462349947*i,y:.297344975250536*e+.6273635662554661*t+.0752914584939979*i,z:.0270313613864123*e+.0706888525358272*t+.9913375368376386*i};return n.alpha!==void 0&&(r.alpha=n.alpha),r},Mm=n=>Math.pow(Math.abs(n),256/563)*Math.sign(n),Lx=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r={mode:"a98",r:Mm(n*2.0415879038107465-e*.5650069742788597-.3447313507783297*t),g:Mm(n*-.9692436362808798+e*1.8759675015077206+.0415550574071756*t),b:Mm(n*.0134442806320312-e*.1183623922310184+1.0151749943912058*t)};return i!==void 0&&(r.alpha=i),r},Sm=(n=0)=>{const e=Math.abs(n);return e<=.04045?n/12.92:(Math.sign(n)||1)*Math.pow((e+.055)/1.055,2.4)},Wa=({r:n,g:e,b:t,alpha:i})=>{let r={mode:"lrgb",r:Sm(n),g:Sm(e),b:Sm(t)};return i!==void 0&&(r.alpha=i),r},Oo=n=>{let{r:e,g:t,b:i,alpha:r}=Wa(n),s={mode:"xyz65",x:.4123907992659593*e+.357584339383878*t+.1804807884018343*i,y:.2126390058715102*e+.715168678767756*t+.0721923153607337*i,z:.0193308187155918*e+.119194779794626*t+.9505321522496607*i};return r!==void 0&&(s.alpha=r),s},Em=(n=0)=>{const e=Math.abs(n);return e>.0031308?(Math.sign(n)||1)*(1.055*Math.pow(e,1/2.4)-.055):n*12.92},Xa=({r:n,g:e,b:t,alpha:i},r="rgb")=>{let s={mode:r,r:Em(n),g:Em(e),b:Em(t)};return i!==void 0&&(s.alpha=i),s},No=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Xa({r:n*3.2409699419045226-e*1.537383177570094-.4986107602930034*t,g:n*-.9692436362808796+e*1.8759675015077204+.0415550574071756*t,b:n*.0556300796969936-e*.2039769588889765+1.0569715142428784*t});return i!==void 0&&(r.alpha=i),r},t6={...Ga,mode:"a98",parse:["a98-rgb"],serialize:"a98-rgb",fromMode:{rgb:n=>Lx(Oo(n)),xyz65:Lx},toMode:{rgb:n=>No(Ix(n)),xyz65:Ix}},_n=n=>(n=n%360)<0?n+360:n,n6=(n,e)=>n.map((t,i,r)=>{if(t===void 0)return t;let s=_n(t);return i===0||n[i-1]===void 0?s:e(s-_n(r[i-1]))}).reduce((t,i)=>!t.length||i===void 0||t[t.length-1]===void 0?(t.push(i),t):(t.push(i+t[t.length-1]),t),[]),Hr=n=>n6(n,e=>Math.abs(e)<=180?e:e-360*Math.sign(e)),ln=[-.14861,1.78277,-.29227,-.90649,1.97294,0],i6=Math.PI/180,r6=180/Math.PI;let Dx=ln[3]*ln[4],Ox=ln[1]*ln[4],Nx=ln[1]*ln[2]-ln[0]*ln[3];const s6=({r:n,g:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=(Nx*t+n*Dx-e*Ox)/(Nx+Dx-Ox),s=t-r,o=(ln[4]*(e-r)-ln[2]*s)/ln[3],a={mode:"cubehelix",l:r,s:r===0||r===1?void 0:Math.sqrt(s*s+o*o)/(ln[4]*r*(1-r))};return a.s&&(a.h=Math.atan2(o,s)*r6-120),i!==void 0&&(a.alpha=i),a},o6=({h:n,s:e,l:t,alpha:i})=>{let r={mode:"rgb"};n=(n===void 0?0:n+120)*i6,t===void 0&&(t=0);let s=e===void 0?0:e*t*(1-t),o=Math.cos(n),a=Math.sin(n);return r.r=t+s*(ln[0]*o+ln[1]*a),r.g=t+s*(ln[2]*o+ln[3]*a),r.b=t+s*(ln[4]*o+ln[5]*a),i!==void 0&&(r.alpha=i),r},Wd=(n,e)=>{if(n.h===void 0||e.h===void 0||!n.s||!e.s)return 0;let t=_n(n.h),i=_n(e.h),r=Math.sin((i-t+360)/2*Math.PI/180);return 2*Math.sqrt(n.s*e.s)*r},a6=(n,e)=>{if(n.h===void 0||e.h===void 0)return 0;let t=_n(n.h),i=_n(e.h);return Math.abs(i-t)>180?t-(i-360*Math.sign(i-t)):i-t},Xd=(n,e)=>{if(n.h===void 0||e.h===void 0||!n.c||!e.c)return 0;let t=_n(n.h),i=_n(e.h),r=Math.sin((i-t+360)/2*Math.PI/180);return 2*Math.sqrt(n.c*e.c)*r},Gr=n=>{let e=n.reduce((i,r)=>{if(r!==void 0){let s=r*Math.PI/180;i.sin+=Math.sin(s),i.cos+=Math.cos(s)}return i},{sin:0,cos:0}),t=Math.atan2(e.sin,e.cos)*180/Math.PI;return t<0?360+t:t},l6={mode:"cubehelix",channels:["h","s","l","alpha"],parse:["--cubehelix"],serialize:"--cubehelix",ranges:{h:[0,360],s:[0,4.614],l:[0,1]},fromMode:{rgb:s6},toMode:{rgb:o6},interpolate:{h:{use:we,fixup:Hr},s:we,l:we,alpha:{use:we,fixup:on}},difference:{h:Wd},average:{h:Gr}},ys=({l:n,a:e,b:t,alpha:i},r="lch")=>{e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.sqrt(e*e+t*t),o={mode:r,l:n,c:s};return s&&(o.h=_n(Math.atan2(t,e)*180/Math.PI)),i!==void 0&&(o.alpha=i),o},bs=({l:n,c:e,h:t,alpha:i},r="lab")=>{t===void 0&&(t=0);let s={mode:r,l:n,a:e?e*Math.cos(t/180*Math.PI):0,b:e?e*Math.sin(t/180*Math.PI):0};return i!==void 0&&(s.alpha=i),s},jw=Math.pow(29,3)/Math.pow(3,3),Kw=Math.pow(6,3)/Math.pow(29,3),Jt={X:.3457/.3585,Y:1,Z:(1-.3457-.3585)/.3585},ya={X:.3127/.329,Y:1,Z:(1-.3127-.329)/.329};let Tm=n=>Math.pow(n,3)>Kw?Math.pow(n,3):(116*n-16)/jw;const Zw=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=(n+16)/116,s=e/500+r,o=r-t/200,a={mode:"xyz65",x:Tm(s)*ya.X,y:Tm(r)*ya.Y,z:Tm(o)*ya.Z};return i!==void 0&&(a.alpha=i),a},$d=n=>No(Zw(n)),wm=n=>n>Kw?Math.cbrt(n):(jw*n+16)/116,Jw=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=wm(n/ya.X),s=wm(e/ya.Y),o=wm(t/ya.Z),a={mode:"lab65",l:116*s-16,a:500*(r-s),b:200*(s-o)};return i!==void 0&&(a.alpha=i),a},qd=n=>{let e=Jw(Oo(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e},Dh=1,Qw=1,Mc=26/180*Math.PI,Oh=Math.cos(Mc),Nh=Math.sin(Mc),eA=100/Math.log(139/100),jg=({l:n,c:e,h:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r={mode:"lab65",l:(Math.exp(n*Dh/eA)-1)/.0039},s=(Math.exp(.0435*e*Qw*Dh)-1)/.075,o=s*Math.cos(t/180*Math.PI-Mc),a=s*Math.sin(t/180*Math.PI-Mc);return r.a=o*Oh-a/.83*Nh,r.b=o*Nh+a/.83*Oh,i!==void 0&&(r.alpha=i),r},Kg=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=e*Oh+t*Nh,s=.83*(t*Oh-e*Nh),o=Math.sqrt(r*r+s*s),a={mode:"dlch",l:eA/Dh*Math.log(1+.0039*n),c:Math.log(1+.075*o)/(.0435*Qw*Dh)};return a.c&&(a.h=_n((Math.atan2(s,r)+Mc)/Math.PI*180)),i!==void 0&&(a.alpha=i),a},Ux=n=>jg(ys(n,"dlch")),Fx=n=>bs(Kg(n),"dlab"),c6={mode:"dlab",parse:["--din99o-lab"],serialize:"--din99o-lab",toMode:{lab65:Ux,rgb:n=>$d(Ux(n))},fromMode:{lab65:Fx,rgb:n=>Fx(qd(n))},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-40.09,45.501],b:[-40.469,44.344]},interpolate:{l:we,a:we,b:we,alpha:{use:we,fixup:on}}},u6={mode:"dlch",parse:["--din99o-lch"],serialize:"--din99o-lch",toMode:{lab65:jg,dlab:n=>bs(n,"dlab"),rgb:n=>$d(jg(n))},fromMode:{lab65:Kg,dlab:n=>ys(n,"dlch"),rgb:n=>Kg(qd(n))},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,51.484],h:[0,360]},interpolate:{l:we,c:we,h:{use:we,fixup:Hr},alpha:{use:we,fixup:on}},difference:{h:Xd},average:{h:Gr}};function f6({h:n,s:e,i:t,alpha:i}){n=_n(n!==void 0?n:0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.abs(n/60%2-1),s;switch(Math.floor(n/60)){case 0:s={r:t*(1+e*(3/(2-r)-1)),g:t*(1+e*(3*(1-r)/(2-r)-1)),b:t*(1-e)};break;case 1:s={r:t*(1+e*(3*(1-r)/(2-r)-1)),g:t*(1+e*(3/(2-r)-1)),b:t*(1-e)};break;case 2:s={r:t*(1-e),g:t*(1+e*(3/(2-r)-1)),b:t*(1+e*(3*(1-r)/(2-r)-1))};break;case 3:s={r:t*(1-e),g:t*(1+e*(3*(1-r)/(2-r)-1)),b:t*(1+e*(3/(2-r)-1))};break;case 4:s={r:t*(1+e*(3*(1-r)/(2-r)-1)),g:t*(1-e),b:t*(1+e*(3/(2-r)-1))};break;case 5:s={r:t*(1+e*(3/(2-r)-1)),g:t*(1-e),b:t*(1+e*(3*(1-r)/(2-r)-1))};break;default:s={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return s.mode="rgb",i!==void 0&&(s.alpha=i),s}function h6({r:n,g:e,b:t,alpha:i}){n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.max(n,e,t),s=Math.min(n,e,t),o={mode:"hsi",s:n+e+t===0?0:1-3*s/(n+e+t),i:(n+e+t)/3};return r-s!==0&&(o.h=(r===n?(e-t)/(r-s)+(e{switch(e){case"deg":return+n;case"rad":return n/Math.PI*180;case"grad":return n/10*9;case"turn":return n*360}},_6=new RegExp(`^hsla?\\(\\s*${NV}${Ia}${Vl}${Ia}${Vl}\\s*(?:,\\s*${z_}\\s*)?\\)$`),v6=n=>{let e=n.match(_6);if(!e)return;let t={mode:"hsl"};return e[3]!==void 0?t.h=+e[3]:e[1]!==void 0&&e[2]!==void 0&&(t.h=g6(e[1],e[2])),e[4]!==void 0&&(t.s=Math.min(Math.max(0,e[4]/100),1)),e[5]!==void 0&&(t.l=Math.min(Math.max(0,e[5]/100),1)),e[6]!==void 0?t.alpha=Math.max(0,Math.min(1,e[6]/100)):e[7]!==void 0&&(t.alpha=Math.max(0,Math.min(1,+e[7]))),t};function y6(n,e){if(!e||e[0]!=="hsl"&&e[0]!=="hsla")return;const t={mode:"hsl"},[,i,r,s,o]=e;if(i.type!==ve.None){if(i.type===ve.Percentage)return;t.h=i.value}if(r.type!==ve.None){if(r.type===ve.Hue)return;t.s=r.value/100}if(s.type!==ve.None){if(s.type===ve.Hue)return;t.l=s.value/100}return o.type!==ve.None&&(t.alpha=Math.min(1,Math.max(0,o.type===ve.Number?o.value:o.value/100))),t}const tA={mode:"hsl",toMode:{rgb:p6},fromMode:{rgb:m6},channels:["h","s","l","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[y6,v6],serialize:n=>`hsl(${n.h!==void 0?n.h:"none"} ${n.s!==void 0?n.s*100+"%":"none"} ${n.l!==void 0?n.l*100+"%":"none"}${n.alpha<1?` / ${n.alpha}`:""})`,interpolate:{h:{use:we,fixup:Hr},s:we,l:we,alpha:{use:we,fixup:on}},difference:{h:Wd},average:{h:Gr}};function nA({h:n,s:e,v:t,alpha:i}){n=_n(n!==void 0?n:0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.abs(n/60%2-1),s;switch(Math.floor(n/60)){case 0:s={r:t,g:t*(1-e*r),b:t*(1-e)};break;case 1:s={r:t*(1-e*r),g:t,b:t*(1-e)};break;case 2:s={r:t*(1-e),g:t,b:t*(1-e*r)};break;case 3:s={r:t*(1-e),g:t*(1-e*r),b:t};break;case 4:s={r:t*(1-e*r),g:t*(1-e),b:t};break;case 5:s={r:t,g:t*(1-e),b:t*(1-e*r)};break;default:s={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return s.mode="rgb",i!==void 0&&(s.alpha=i),s}function iA({r:n,g:e,b:t,alpha:i}){n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.max(n,e,t),s=Math.min(n,e,t),o={mode:"hsv",s:r===0?0:1-s/r,v:r};return r-s!==0&&(o.h=(r===n?(e-t)/(r-s)+(e1){let r=e+t;e/=r,t/=r}return nA({h:n,s:t===1?1:1-e/(1-t),v:1-t,alpha:i})}function x6(n){let e=iA(n);if(e===void 0)return;let t=e.s!==void 0?e.s:0,i=e.v!==void 0?e.v:0,r={mode:"hwb",w:(1-t)*i,b:1-i};return e.h!==void 0&&(r.h=e.h),e.alpha!==void 0&&(r.alpha=e.alpha),r}function M6(n,e){if(!e||e[0]!=="hwb")return;const t={mode:"hwb"},[,i,r,s,o]=e;if(i.type!==ve.None){if(i.type===ve.Percentage)return;t.h=i.value}if(r.type!==ve.None){if(r.type===ve.Hue)return;t.w=r.value/100}if(s.type!==ve.None){if(s.type===ve.Hue)return;t.b=s.value/100}return o.type!==ve.None&&(t.alpha=Math.min(1,Math.max(0,o.type===ve.Number?o.value:o.value/100))),t}const S6={mode:"hwb",toMode:{rgb:b6},fromMode:{rgb:x6},channels:["h","w","b","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[M6],serialize:n=>`hwb(${n.h!==void 0?n.h:"none"} ${n.w!==void 0?n.w*100+"%":"none"} ${n.b!==void 0?n.b*100+"%":"none"}${n.alpha<1?` / ${n.alpha}`:""})`,interpolate:{h:{use:we,fixup:Hr},w:we,b:we,alpha:{use:we,fixup:on}},difference:{h:a6},average:{h:Gr}},sA=203,Yd=.1593017578125,oA=78.84375,jd=.8359375,Kd=18.8515625,Zd=18.6875;function Am(n){if(n<0)return 0;const e=Math.pow(n,1/oA);return 1e4*Math.pow(Math.max(0,e-jd)/(Kd-Zd*e),1/Yd)}function Cm(n){if(n<0)return 0;const e=Math.pow(n/1e4,Yd);return Math.pow((jd+Kd*e)/(1+Zd*e),oA)}const Rm=n=>Math.max(n/sA,0),kx=({i:n,t:e,p:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const r=Am(n+.008609037037932761*e+.11102962500302593*t),s=Am(n-.00860903703793275*e-.11102962500302599*t),o=Am(n+.5600313357106791*e-.32062717498731885*t),a={mode:"xyz65",x:Rm(2.070152218389422*r-1.3263473389671556*s+.2066510476294051*o),y:Rm(.3647385209748074*r+.680566024947227*s-.0453045459220346*o),z:Rm(-.049747207535812*r-.0492609666966138*s+1.1880659249923042*o)};return i!==void 0&&(a.alpha=i),a},Pm=(n=0)=>Math.max(n*sA,0),Bx=({x:n,y:e,z:t,alpha:i})=>{const r=Pm(n),s=Pm(e),o=Pm(t),a=Cm(.3592832590121217*r+.6976051147779502*s-.0358915932320289*o),l=Cm(-.1920808463704995*r+1.1004767970374323*s+.0753748658519118*o),c=Cm(.0070797844607477*r+.0748396662186366*s+.8433265453898765*o),u=.5*a+.5*l,f=1.61376953125*a-3.323486328125*l+1.709716796875*c,h=4.378173828125*a-4.24560546875*l-.132568359375*c,d={mode:"itp",i:u,t:f,p:h};return i!==void 0&&(d.alpha=i),d},E6={mode:"itp",channels:["i","t","p","alpha"],parse:["--ictcp"],serialize:"--ictcp",toMode:{xyz65:kx,rgb:n=>No(kx(n))},fromMode:{xyz65:Bx,rgb:n=>Bx(Oo(n))},ranges:{i:[0,.581],t:[-.369,.272],p:[-.164,.331]},interpolate:{i:we,t:we,p:we,alpha:{use:we,fixup:on}}},T6=134.03437499999998,w6=16295499532821565e-27,Im=n=>{if(n<0)return 0;let e=Math.pow(n/1e4,Yd);return Math.pow((jd+Kd*e)/(1+Zd*e),T6)},Lm=(n=0)=>Math.max(n*203,0),aA=({x:n,y:e,z:t,alpha:i})=>{n=Lm(n),e=Lm(e),t=Lm(t);let r=1.15*n-.15*t,s=.66*e+.34*n,o=Im(.41478972*r+.579999*s+.014648*t),a=Im(-.20151*r+1.120649*s+.0531008*t),l=Im(-.0166008*r+.2648*s+.6684799*t),c=(o+a)/2,u={mode:"jab",j:.44*c/(1-.56*c)-w6,a:3.524*o-4.066708*a+.542708*l,b:.199076*o+1.096799*a-1.295875*l};return i!==void 0&&(u.alpha=i),u},A6=134.03437499999998,zx=16295499532821565e-27,Dm=n=>{if(n<0)return 0;let e=Math.pow(n,1/A6);return 1e4*Math.pow((jd-e)/(Zd*e-Kd),1/Yd)},Om=n=>n/203,lA=({j:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=(n+zx)/(.44+.56*(n+zx)),s=Dm(r+.13860504*e+.058047316*t),o=Dm(r-.13860504*e-.058047316*t),a=Dm(r-.096019242*e-.8118919*t),l={mode:"xyz65",x:Om(1.661373024652174*s-.914523081304348*o+.23136208173913045*a),y:Om(-.3250758611844533*s+1.571847026732543*o-.21825383453227928*a),z:Om(-.090982811*s-.31272829*o+1.5227666*a)};return i!==void 0&&(l.alpha=i),l},cA=n=>{let e=aA(Oo(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e},uA=n=>No(lA(n)),C6={mode:"jab",channels:["j","a","b","alpha"],parse:["--jzazbz"],serialize:"--jzazbz",fromMode:{rgb:cA,xyz65:aA},toMode:{rgb:uA,xyz65:lA},ranges:{j:[0,.222],a:[-.109,.129],b:[-.185,.134]},interpolate:{j:we,a:we,b:we,alpha:{use:we,fixup:on}}},Vx=({j:n,a:e,b:t,alpha:i})=>{e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.sqrt(e*e+t*t),s={mode:"jch",j:n,c:r};return r&&(s.h=_n(Math.atan2(t,e)*180/Math.PI)),i!==void 0&&(s.alpha=i),s},Hx=({j:n,c:e,h:t,alpha:i})=>{t===void 0&&(t=0);let r={mode:"jab",j:n,a:e?e*Math.cos(t/180*Math.PI):0,b:e?e*Math.sin(t/180*Math.PI):0};return i!==void 0&&(r.alpha=i),r},R6={mode:"jch",parse:["--jzczhz"],serialize:"--jzczhz",toMode:{jab:Hx,rgb:n=>uA(Hx(n))},fromMode:{rgb:n=>Vx(cA(n)),jab:Vx},channels:["j","c","h","alpha"],ranges:{j:[0,.221],c:[0,.19],h:[0,360]},interpolate:{h:{use:we,fixup:Hr},c:we,j:we,alpha:{use:we,fixup:on}},difference:{h:Xd},average:{h:Gr}},Jd=Math.pow(29,3)/Math.pow(3,3),V_=Math.pow(6,3)/Math.pow(29,3);let Nm=n=>Math.pow(n,3)>V_?Math.pow(n,3):(116*n-16)/Jd;const H_=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=(n+16)/116,s=e/500+r,o=r-t/200,a={mode:"xyz50",x:Nm(s)*Jt.X,y:Nm(r)*Jt.Y,z:Nm(o)*Jt.Z};return i!==void 0&&(a.alpha=i),a},Kc=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Xa({r:n*3.1341359569958707-e*1.6173863321612538-.4906619460083532*t,g:n*-.978795502912089+e*1.916254567259524+.03344273116131949*t,b:n*.07195537988411677-e*.2289768264158322+1.405386058324125*t});return i!==void 0&&(r.alpha=i),r},fA=n=>Kc(H_(n)),Zc=n=>{let{r:e,g:t,b:i,alpha:r}=Wa(n),s={mode:"xyz50",x:.436065742824811*e+.3851514688337912*t+.14307845442264197*i,y:.22249319175623702*e+.7168870538238823*t+.06061979053616537*i,z:.013923904500943465*e+.09708128566574634*t+.7140993584005155*i};return r!==void 0&&(s.alpha=r),s},Um=n=>n>V_?Math.cbrt(n):(Jd*n+16)/116,G_=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Um(n/Jt.X),s=Um(e/Jt.Y),o=Um(t/Jt.Z),a={mode:"lab",l:116*s-16,a:500*(r-s),b:200*(s-o)};return i!==void 0&&(a.alpha=i),a},hA=n=>{let e=G_(Zc(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e};function P6(n,e){if(!e||e[0]!=="lab")return;const t={mode:"lab"},[,i,r,s,o]=e;if(!(i.type===ve.Hue||r.type===ve.Hue||s.type===ve.Hue))return i.type!==ve.None&&(t.l=Math.min(Math.max(0,i.value),100)),r.type!==ve.None&&(t.a=r.type===ve.Number?r.value:r.value*125/100),s.type!==ve.None&&(t.b=s.type===ve.Number?s.value:s.value*125/100),o.type!==ve.None&&(t.alpha=Math.min(1,Math.max(0,o.type===ve.Number?o.value:o.value/100))),t}const W_={mode:"lab",toMode:{xyz50:H_,rgb:fA},fromMode:{xyz50:G_,rgb:hA},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-100,100],b:[-100,100]},parse:[P6],serialize:n=>`lab(${n.l!==void 0?n.l:"none"} ${n.a!==void 0?n.a:"none"} ${n.b!==void 0?n.b:"none"}${n.alpha<1?` / ${n.alpha}`:""})`,interpolate:{l:we,a:we,b:we,alpha:{use:we,fixup:on}}},I6={...W_,mode:"lab65",parse:["--lab-d65"],serialize:"--lab-d65",toMode:{xyz65:Zw,rgb:$d},fromMode:{xyz65:Jw,rgb:qd},ranges:{l:[0,100],a:[-86.182,98.234],b:[-107.86,94.477]}};function L6(n,e){if(!e||e[0]!=="lch")return;const t={mode:"lch"},[,i,r,s,o]=e;if(i.type!==ve.None){if(i.type===ve.Hue)return;t.l=Math.min(Math.max(0,i.value),100)}if(r.type!==ve.None&&(t.c=Math.max(0,r.type===ve.Number?r.value:r.value*150/100)),s.type!==ve.None){if(s.type===ve.Percentage)return;t.h=s.value}return o.type!==ve.None&&(t.alpha=Math.min(1,Math.max(0,o.type===ve.Number?o.value:o.value/100))),t}const X_={mode:"lch",toMode:{lab:bs,rgb:n=>fA(bs(n))},fromMode:{rgb:n=>ys(hA(n)),lab:ys},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,150],h:[0,360]},parse:[L6],serialize:n=>`lch(${n.l!==void 0?n.l:"none"} ${n.c!==void 0?n.c:"none"} ${n.h!==void 0?n.h:"none"}${n.alpha<1?` / ${n.alpha}`:""})`,interpolate:{h:{use:we,fixup:Hr},c:we,l:we,alpha:{use:we,fixup:on}},difference:{h:Xd},average:{h:Gr}},D6={...X_,mode:"lch65",parse:["--lch-d65"],serialize:"--lch-d65",toMode:{lab65:n=>bs(n,"lab65"),rgb:n=>$d(bs(n,"lab65"))},fromMode:{rgb:n=>ys(qd(n),"lch65"),lab65:n=>ys(n,"lch65")},ranges:{l:[0,100],c:[0,133.807],h:[0,360]}},dA=({l:n,u:e,v:t,alpha:i})=>{e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.sqrt(e*e+t*t),s={mode:"lchuv",l:n,c:r};return r&&(s.h=_n(Math.atan2(t,e)*180/Math.PI)),i!==void 0&&(s.alpha=i),s},pA=({l:n,c:e,h:t,alpha:i})=>{t===void 0&&(t=0);let r={mode:"luv",l:n,u:e?e*Math.cos(t/180*Math.PI):0,v:e?e*Math.sin(t/180*Math.PI):0};return i!==void 0&&(r.alpha=i),r},mA=(n,e,t)=>4*n/(n+15*e+3*t),gA=(n,e,t)=>9*e/(n+15*e+3*t),O6=mA(Jt.X,Jt.Y,Jt.Z),N6=gA(Jt.X,Jt.Y,Jt.Z),U6=n=>n<=V_?Jd*n:116*Math.cbrt(n)-16,Zg=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=U6(e/Jt.Y),s=mA(n,e,t),o=gA(n,e,t);!isFinite(s)||!isFinite(o)?r=s=o=0:(s=13*r*(s-O6),o=13*r*(o-N6));let a={mode:"luv",l:r,u:s,v:o};return i!==void 0&&(a.alpha=i),a},F6=(n,e,t)=>4*n/(n+15*e+3*t),k6=(n,e,t)=>9*e/(n+15*e+3*t),B6=F6(Jt.X,Jt.Y,Jt.Z),z6=k6(Jt.X,Jt.Y,Jt.Z),Jg=({l:n,u:e,v:t,alpha:i})=>{if(n===void 0&&(n=0),n===0)return{mode:"xyz50",x:0,y:0,z:0};e===void 0&&(e=0),t===void 0&&(t=0);let r=e/(13*n)+B6,s=t/(13*n)+z6,o=Jt.Y*(n<=8?n/Jd:Math.pow((n+16)/116,3)),a=o*(9*r)/(4*s),l=o*(12-3*r-20*s)/(4*s),c={mode:"xyz50",x:a,y:o,z:l};return i!==void 0&&(c.alpha=i),c},V6=n=>dA(Zg(Zc(n))),H6=n=>Kc(Jg(pA(n))),G6={mode:"lchuv",toMode:{luv:pA,rgb:H6},fromMode:{rgb:V6,luv:dA},channels:["l","c","h","alpha"],parse:["--lchuv"],serialize:"--lchuv",ranges:{l:[0,100],c:[0,176.956],h:[0,360]},interpolate:{h:{use:we,fixup:Hr},c:we,l:we,alpha:{use:we,fixup:on}},difference:{h:Xd},average:{h:Gr}},W6={...Ga,mode:"lrgb",toMode:{rgb:Xa},fromMode:{rgb:Wa},parse:["srgb-linear"],serialize:"srgb-linear"},X6={mode:"luv",toMode:{xyz50:Jg,rgb:n=>Kc(Jg(n))},fromMode:{xyz50:Zg,rgb:n=>Zg(Zc(n))},channels:["l","u","v","alpha"],parse:["--luv"],serialize:"--luv",ranges:{l:[0,100],u:[-84.936,175.042],v:[-125.882,87.243]},interpolate:{l:we,u:we,v:we,alpha:{use:we,fixup:on}}},_A=({r:n,g:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.cbrt(.41222147079999993*n+.5363325363*e+.0514459929*t),s=Math.cbrt(.2119034981999999*n+.6806995450999999*e+.1073969566*t),o=Math.cbrt(.08830246189999998*n+.2817188376*e+.6299787005000002*t),a={mode:"oklab",l:.2104542553*r+.793617785*s-.0040720468*o,a:1.9779984951*r-2.428592205*s+.4505937099*o,b:.0259040371*r+.7827717662*s-.808675766*o};return i!==void 0&&(a.alpha=i),a},Qd=n=>{let e=_A(Wa(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e},Jc=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.pow(n*.9999999984505198+.39633779217376786*e+.2158037580607588*t,3),s=Math.pow(n*1.0000000088817609-.10556134232365635*e-.06385417477170591*t,3),o=Math.pow(n*1.0000000546724108-.08948418209496575*e-1.2914855378640917*t,3),a={mode:"lrgb",r:4.076741661347994*r-3.307711590408193*s+.230969928729428*o,g:-1.2684380040921763*r+2.6097574006633715*s-.3413193963102197*o,b:-.004196086541837188*r-.7034186144594493*s+1.7076147009309444*o};return i!==void 0&&(a.alpha=i),a},ep=n=>Xa(Jc(n));function Qg(n){const i=1.170873786407767;return .5*(i*n-.206+Math.sqrt((i*n-.206)*(i*n-.206)+4*.03*i*n))}function Uh(n){return(n*n+.206*n)/(1.170873786407767*(n+.03))}function $6(n,e){let t,i,r,s,o,a,l,c;-1.88170328*n-.80936493*e>1?(t=1.19086277,i=1.76576728,r=.59662641,s=.75515197,o=.56771245,a=4.0767416621,l=-3.3077115913,c=.2309699292):1.81444104*n-1.19445276*e>1?(t=.73956515,i=-.45954404,r=.08285427,s=.1254107,o=.14503204,a=-1.2684380046,l=2.6097574011,c=-.3413193965):(t=1.35733652,i=-.00915799,r=-1.1513021,s=-.50559606,o=.00692167,a=-.0041960863,l=-.7034186147,c=1.707614701);let u=t+i*n+r*e+s*n*n+o*n*e,f=.3963377774*n+.2158037573*e,h=-.1055613458*n-.0638541728*e,d=-.0894841775*n-1.291485548*e;{let p=1+u*f,_=1+u*h,g=1+u*d,m=p*p*p,y=_*_*_,b=g*g*g,v=3*f*p*p,E=3*h*_*_,T=3*d*g*g,S=6*f*f*p,R=6*h*h*_,x=6*d*d*g,M=a*m+l*y+c*b,L=a*v+l*E+c*T,F=a*S+l*R+c*x;u=u-M*L/(L*L-.5*M*F)}return u}function $_(n,e){let t=$6(n,e),i=Jc({l:1,a:t*n,b:t*e}),r=Math.cbrt(1/Math.max(i.r,i.g,i.b)),s=r*t;return[r,s]}function q6(n,e,t,i,r,s=null){s||(s=$_(n,e));let o;if((t-r)*s[1]-(s[0]-r)*i<=0)o=s[1]*r/(i*s[0]+s[1]*(r-t));else{o=s[1]*(r-1)/(i*(s[0]-1)+s[1]*(r-t));{let a=t-r,l=i,c=.3963377774*n+.2158037573*e,u=-.1055613458*n-.0638541728*e,f=-.0894841775*n-1.291485548*e,h=a+l*c,d=a+l*u,p=a+l*f;{let _=r*(1-o)+o*t,g=o*i,m=_+g*c,y=_+g*u,b=_+g*f,v=m*m*m,E=y*y*y,T=b*b*b,S=3*h*m*m,R=3*d*y*y,x=3*p*b*b,M=6*h*h*m,L=6*d*d*y,F=6*p*p*b,V=4.0767416621*v-3.3077115913*E+.2309699292*T-1,X=4.0767416621*S-3.3077115913*R+.2309699292*x,te=4.0767416621*M-3.3077115913*L+.2309699292*F,Z=X/(X*X-.5*V*te),ee=-V*Z,Q=-1.2684380046*v+2.6097574011*E-.3413193965*T-1,de=-1.2684380046*S+2.6097574011*R-.3413193965*x,be=-1.2684380046*M+2.6097574011*L-.3413193965*F,re=de/(de*de-.5*Q*be),ye=-Q*re,Ve=-.0041960863*v-.7034186147*E+1.707614701*T-1,se=-.0041960863*S-.7034186147*R+1.707614701*x,ge=-.0041960863*M-.7034186147*L+1.707614701*F,Me=se/(se*se-.5*Ve*ge),W=-Ve*Me;ee=Z>=0?ee:1e6,ye=re>=0?ye:1e6,W=Me>=0?W:1e6,o+=Math.min(ee,Math.min(ye,W))}}}return o}function q_(n,e,t=null){t||(t=$_(n,e));let i=t[0],r=t[1];return[r/i,r/(1-i)]}function vA(n,e,t){let i=$_(e,t),r=q6(e,t,n,1,n,i),s=q_(e,t,i),o=.11516993+1/(7.4477897+4.1590124*t+e*(-2.19557347+1.75198401*t+e*(-2.13704948-10.02301043*t+e*(-4.24894561+5.38770819*t+4.69891013*e)))),a=.11239642+1/(1.6132032-.68124379*t+e*(.40370612+.90148123*t+e*(-.27087943+.6122399*t+e*(.00299215-.45399568*t-.14661872*e)))),l=r/Math.min(n*s[0],(1-n)*s[1]),c=n*o,u=(1-n)*a,f=.9*l*Math.sqrt(Math.sqrt(1/(1/(c*c*c*c)+1/(u*u*u*u))));return c=n*.4,u=(1-n)*.8,[Math.sqrt(1/(1/(c*c)+1/(u*u))),f,r]}function Gx(n){const e=n.l!==void 0?n.l:0,t=n.a!==void 0?n.a:0,i=n.b!==void 0?n.b:0,r={mode:"okhsl",l:Qg(e)};n.alpha!==void 0&&(r.alpha=n.alpha);let s=Math.sqrt(t*t+i*i);if(!s)return r.s=0,r;let[o,a,l]=vA(e,t/s,i/s),c;if(sGx(Qd(n))},toMode:{oklab:Wx,rgb:n=>ep(Wx(n))}};function Xx(n){let e=n.l!==void 0?n.l:0,t=n.a!==void 0?n.a:0,i=n.b!==void 0?n.b:0,r=Math.sqrt(t*t+i*i),s=r?t/r:1,o=r?i/r:1,[a,l]=q_(s,o),c=.5,u=1-c/a,f=l/(r+e*l),h=f*e,d=f*r,p=Uh(h),_=d*p/h,g=Jc({l:p,a:s*_,b:o*_}),m=Math.cbrt(1/Math.max(g.r,g.g,g.b,0));e=e/m,r=r/m*Qg(e)/e,e=Qg(e);const y={mode:"okhsv",s:r?(c+l)*d/(l*c+l*u*d):0,v:e?e/h:0};return y.s&&(y.h=_n(Math.atan2(i,t)*180/Math.PI)),n.alpha!==void 0&&(y.alpha=n.alpha),y}function $x(n){const e={mode:"oklab"};n.alpha!==void 0&&(e.alpha=n.alpha);const t=n.h!==void 0?n.h:0,i=n.s!==void 0?n.s:0,r=n.v!==void 0?n.v:0,s=Math.cos(t/180*Math.PI),o=Math.sin(t/180*Math.PI),[a,l]=q_(s,o),c=.5,u=1-c/a,f=1-i*c/(c+l-l*u*i),h=i*l*c/(c+l-l*u*i),d=Uh(f),p=h*d/f,_=Jc({l:d,a:s*p,b:o*p}),g=Math.cbrt(1/Math.max(_.r,_.g,_.b,0)),m=Uh(r*f),y=h*m/f;return e.l=m*g,e.a=y*s*g,e.b=y*o*g,e}const j6={...rA,mode:"okhsv",channels:["h","s","v","alpha"],parse:["--okhsv"],serialize:"--okhsv",fromMode:{oklab:Xx,rgb:n=>Xx(Qd(n))},toMode:{oklab:$x,rgb:n=>ep($x(n))}};function K6(n,e){if(!e||e[0]!=="oklab")return;const t={mode:"oklab"},[,i,r,s,o]=e;if(!(i.type===ve.Hue||r.type===ve.Hue||s.type===ve.Hue))return i.type!==ve.None&&(t.l=Math.min(Math.max(0,i.type===ve.Number?i.value:i.value/100),1)),r.type!==ve.None&&(t.a=r.type===ve.Number?r.value:r.value*.4/100),s.type!==ve.None&&(t.b=s.type===ve.Number?s.value:s.value*.4/100),o.type!==ve.None&&(t.alpha=Math.min(1,Math.max(0,o.type===ve.Number?o.value:o.value/100))),t}const Z6={...W_,mode:"oklab",toMode:{lrgb:Jc,rgb:ep},fromMode:{lrgb:_A,rgb:Qd},ranges:{l:[0,1],a:[-.4,.4],b:[-.4,.4]},parse:[K6],serialize:n=>`oklab(${n.l!==void 0?n.l:"none"} ${n.a!==void 0?n.a:"none"} ${n.b!==void 0?n.b:"none"}${n.alpha<1?` / ${n.alpha}`:""})`};function J6(n,e){if(!e||e[0]!=="oklch")return;const t={mode:"oklch"},[,i,r,s,o]=e;if(i.type!==ve.None){if(i.type===ve.Hue)return;t.l=Math.min(Math.max(0,i.type===ve.Number?i.value:i.value/100),1)}if(r.type!==ve.None&&(t.c=Math.max(0,r.type===ve.Number?r.value:r.value*.4/100)),s.type!==ve.None){if(s.type===ve.Percentage)return;t.h=s.value}return o.type!==ve.None&&(t.alpha=Math.min(1,Math.max(0,o.type===ve.Number?o.value:o.value/100))),t}const Q6={...X_,mode:"oklch",toMode:{oklab:n=>bs(n,"oklab"),rgb:n=>ep(bs(n,"oklab"))},fromMode:{rgb:n=>ys(Qd(n),"oklch"),oklab:n=>ys(n,"oklch")},parse:[J6],serialize:n=>`oklch(${n.l!==void 0?n.l:"none"} ${n.c!==void 0?n.c:"none"} ${n.h!==void 0?n.h:"none"}${n.alpha<1?` / ${n.alpha}`:""})`,ranges:{l:[0,1],c:[0,.4],h:[0,360]}},qx=n=>{let{r:e,g:t,b:i,alpha:r}=Wa(n),s={mode:"xyz65",x:.486570948648216*e+.265667693169093*t+.1982172852343625*i,y:.2289745640697487*e+.6917385218365062*t+.079286914093745*i,z:0*e+.0451133818589026*t+1.043944368900976*i};return r!==void 0&&(s.alpha=r),s},Yx=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r=Xa({r:n*2.4934969119414263-e*.9313836179191242-.402710784450717*t,g:n*-.8294889695615749+e*1.7626640603183465+.0236246858419436*t,b:n*.0358458302437845-e*.0761723892680418+.9568845240076871*t},"p3");return i!==void 0&&(r.alpha=i),r},eH={...Ga,mode:"p3",parse:["display-p3"],serialize:"display-p3",fromMode:{rgb:n=>Yx(Oo(n)),xyz65:Yx},toMode:{rgb:n=>No(qx(n)),xyz65:qx}},Fm=n=>{let e=Math.abs(n);return e>=1/512?Math.sign(n)*Math.pow(e,1/1.8):16*n},jx=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r={mode:"prophoto",r:Fm(n*1.3457868816471585-e*.2555720873797946-.0511018649755453*t),g:Fm(n*-.5446307051249019+e*1.5082477428451466+.0205274474364214*t),b:Fm(n*0+e*0+1.2119675456389452*t)};return i!==void 0&&(r.alpha=i),r},km=(n=0)=>{let e=Math.abs(n);return e>=16/512?Math.sign(n)*Math.pow(e,1.8):n/16},Kx=n=>{let e=km(n.r),t=km(n.g),i=km(n.b),r={mode:"xyz50",x:.7977666449006423*e+.1351812974005331*t+.0313477341283922*i,y:.2880748288194013*e+.7118352342418731*t+899369387256e-16*i,z:0*e+0*t+.8251046025104602*i};return n.alpha!==void 0&&(r.alpha=n.alpha),r},tH={...Ga,mode:"prophoto",parse:["prophoto-rgb"],serialize:"prophoto-rgb",fromMode:{xyz50:jx,rgb:n=>jx(Zc(n))},toMode:{xyz50:Kx,rgb:n=>Kc(Kx(n))}},Zx=1.09929682680944,nH=.018053968510807,Bm=n=>{const e=Math.abs(n);return e>nH?(Math.sign(n)||1)*(Zx*Math.pow(e,.45)-(Zx-1)):4.5*n},Jx=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let r={mode:"rec2020",r:Bm(n*1.7166511879712683-e*.3556707837763925-.2533662813736599*t),g:Bm(n*-.6666843518324893+e*1.6164812366349395+.0157685458139111*t),b:Bm(n*.0176398574453108-e*.0427706132578085+.9421031212354739*t)};return i!==void 0&&(r.alpha=i),r},Qx=1.09929682680944,iH=.018053968510807,zm=(n=0)=>{let e=Math.abs(n);return e{let e=zm(n.r),t=zm(n.g),i=zm(n.b),r={mode:"xyz65",x:.6369580483012911*e+.1446169035862083*t+.1688809751641721*i,y:.262700212011267*e+.6779980715188708*t+.059301716469862*i,z:0*e+.0280726930490874*t+1.0609850577107909*i};return n.alpha!==void 0&&(r.alpha=n.alpha),r},rH={...Ga,mode:"rec2020",fromMode:{xyz65:Jx,rgb:n=>Jx(Oo(n))},toMode:{xyz65:eM,rgb:n=>No(eM(n))},parse:["rec2020"],serialize:"rec2020"},vo=.0037930732552754493,yA=Math.cbrt(vo),Vm=n=>Math.cbrt(n)-yA,sH=n=>{const{r:e,g:t,b:i,alpha:r}=Wa(n),s=Vm(.3*e+.622*t+.078*i+vo),o=Vm(.23*e+.692*t+.078*i+vo),a=Vm(.2434226892454782*e+.2047674442449682*t+.5518098665095535*i+vo),l={mode:"xyb",x:(s-o)/2,y:(s+o)/2,b:a-(s+o)/2};return r!==void 0&&(l.alpha=r),l},Hm=n=>Math.pow(n+yA,3),oH=({x:n,y:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const r=Hm(n+e)-vo,s=Hm(e-n)-vo,o=Hm(t+e)-vo,a=Xa({r:11.031566904639861*r-9.866943908131562*s-.16462299650829934*o,g:-3.2541473810744237*r+4.418770377582723*s-.16462299650829934*o,b:-3.6588512867136815*r+2.7129230459360922*s+1.9459282407775895*o});return i!==void 0&&(a.alpha=i),a},aH={mode:"xyb",channels:["x","y","b","alpha"],parse:["--xyb"],serialize:"--xyb",toMode:{rgb:oH},fromMode:{rgb:sH},ranges:{x:[-.0154,.0281],y:[0,.8453],b:[-.2778,.388]},interpolate:{x:we,y:we,b:we,alpha:{use:we,fixup:on}}},lH={mode:"xyz50",parse:["xyz-d50"],serialize:"xyz-d50",toMode:{rgb:Kc,lab:G_},fromMode:{rgb:Zc,lab:H_},channels:["x","y","z","alpha"],ranges:{x:[0,.964],y:[0,.999],z:[0,.825]},interpolate:{x:we,y:we,z:we,alpha:{use:we,fixup:on}}},cH=n=>{let{x:e,y:t,z:i,alpha:r}=n;e===void 0&&(e=0),t===void 0&&(t=0),i===void 0&&(i=0);let s={mode:"xyz50",x:1.0479298208405488*e+.0229467933410191*t-.0501922295431356*i,y:.0296278156881593*e+.990434484573249*t-.0170738250293851*i,z:-.0092430581525912*e+.0150551448965779*t+.7518742899580008*i};return r!==void 0&&(s.alpha=r),s},uH=n=>{let{x:e,y:t,z:i,alpha:r}=n;e===void 0&&(e=0),t===void 0&&(t=0),i===void 0&&(i=0);let s={mode:"xyz65",x:.9554734527042182*e-.0230985368742614*t+.0632593086610217*i,y:-.0283697069632081*e+1.0099954580058226*t+.021041398966943*i,z:.0123140016883199*e-.0205076964334779*t+1.3303659366080753*i};return r!==void 0&&(s.alpha=r),s},fH={mode:"xyz65",toMode:{rgb:No,xyz50:cH},fromMode:{rgb:Oo,xyz50:uH},ranges:{x:[0,.95],y:[0,1],z:[0,1.088]},channels:["x","y","z","alpha"],parse:["xyz","xyz-d65"],serialize:"xyz-d65",interpolate:{x:we,y:we,z:we,alpha:{use:we,fixup:on}}},hH=({r:n,g:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const r={mode:"yiq",y:.29889531*n+.58662247*e+.11448223*t,i:.59597799*n-.2741761*e-.32180189*t,q:.21147017*n-.52261711*e+.31114694*t};return i!==void 0&&(r.alpha=i),r},dH=({y:n,i:e,q:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const r={mode:"rgb",r:n+.95608445*e+.6208885*t,g:n-.27137664*e-.6486059*t,b:n-1.10561724*e+1.70250126*t};return i!==void 0&&(r.alpha=i),r},pH={mode:"yiq",toMode:{rgb:dH},fromMode:{rgb:hH},channels:["y","i","q","alpha"],parse:["--yiq"],serialize:"--yiq",ranges:{i:[-.595,.595],q:[-.522,.522]},interpolate:{y:we,i:we,q:we,alpha:{use:we,fixup:on}}};Et(t6);Et(l6);Et(c6);Et(u6);Et(d6);Et(tA);Et(rA);Et(S6);Et(E6);Et(C6);Et(R6);Et(W_);Et(I6);Et(X_);Et(D6);Et(G6);Et(W6);Et(X6);Et(Y6);Et(j6);Et(Z6);Et(Q6);Et(eH);Et(tH);Et(rH);Et(Ga);Et(aH);Et(lH);Et(fH);Et(pH);const e0=178.17,mH=Xw("oklch"),tM=n=>{var e;return n?(e=mH(n))==null?void 0:e.h:e0},gH=Sz("settings",()=>{const n=et(),e=mr("settings/language","en-US"),t=mr("settings/stage/view/model-renderer","2d"),i=mr("settings/audio/input","true"),r=Se(()=>{var E;return(E=n.value)==null?void 0:E.deviceId}),{audioInputs:s}=AB({constraints:{audio:!0},requestPermissions:!0}),o=et(),a=et("/assets/live2d/models/hiyori_pro_zh.zip"),l=et("url"),c=et(!1),u=mr("settings/live2d/position",{x:0,y:0}),f=et({group:"Idle",index:0}),h=et([]),d=mr("settings/live2d/motion-map",{}),p=mr("settings/disable-transitions",!0),_=mr("settings/use-page-specific-transitions",!0),g=mr("settings/theme/colors/hue",e0),m=mr("settings/theme/colors/hue-dynamic",!1);function y(E=e0){g.value=E,m.value=!1}function b(E){y(tM(E))}function v(E){if(m.value)return!1;const T=tM(E);if(!T)return!1;const S=Math.abs(T-g.value);return S<.01||S>359.99}return Xe(i,E=>{E==="false"&&(n.value=void 0),E==="true"&&(n.value=s.value[0])}),Xe(s,()=>{i.value==="true"&&!n.value&&(n.value=s.value[0])},{immediate:!0}),{live2dModelFile:o,live2dModelUrl:a,live2dLoadSource:l,live2dCurrentMotion:f,live2dPosition:u,availableLive2dMotions:h,live2dMotionMap:d,loadingLive2dModel:c,disableTransitions:p,usePageSpecificTransitions:_,language:e,stageView:t,themeColorsHue:g,themeColorsHueDynamic:m,isAudioInputOn:i,selectedAudioDevice:n,selectedAudioDeviceId:r,setThemeColorsHue:y,applyPrimaryColorFrom:b,isColorSelectedForPrimary:v}}),_H=fn({__name:"ArrowTransition",props:{stageTransition:{default:()=>({primaryColor:"#666",secondaryColor:"#ccc"})}},setup(n){const e=n,t=Se(()=>e.stageTransition),i=Se(()=>t.value.primaryColor||"#666"),r=Se(()=>t.value.secondaryColor||"#ccc");return Hn(()=>{document.documentElement.style.setProperty("--stage-transition-3-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-3-overlay-color-2",r.value)}),(s,o)=>(mn(),vi("div",{class:"stage-transition-3",style:Si({zIndex:t.value.zIndex||100})},null,4))}}),Uo=(n,e)=>{const t=n.__vccOpts||n;for(const[i,r]of e)t[i]=r;return t},vH=Uo(_H,[["__scopeId","data-v-df576df0"]]),yH=fn({__name:"BubbleWaveOutTransition",props:{stageTransition:null},setup(n){const e=n,t=Se(()=>{var i;return((i=e.stageTransition)==null?void 0:i.colors)||["#eee","#ebcb8b","#c56370","#3f3b52"]});return Hn(()=>{var i,r;document.documentElement.style.setProperty("--circle-expansion-delay",`${((i=e.stageTransition)==null?void 0:i.delay)||0}s`),document.documentElement.style.setProperty("--circle-expansion-duration",`${((r=e.stageTransition)==null?void 0:r.duration)||.4}s`),t.value.forEach((s,o)=>{document.documentElement.style.setProperty(`--circle-expansion-color-${o+1}`,s)})}),(i,r)=>{var s;return mn(),vi("div",{class:"circle-expansion-transition",style:Si({zIndex:((s=n.stageTransition)==null?void 0:s.zIndex)||100})},[(mn(!0),vi(jt,null,eR(t.value,(o,a)=>(mn(),vi("div",{key:a}))),128))],4)}}}),bH=Uo(yH,[["__scopeId","data-v-0c29056c"]]),xH=fn({__name:"FantasyFallTransition",props:{stageTransition:null},setup(n){const e=n,t=Se(()=>{var r;return((r=e.stageTransition)==null?void 0:r.direction)||"up"}),i=Se(()=>`fantasy-fall-${t.value}`);return Hn(()=>{var r,s,o,a,l,c,u,f,h;document.documentElement.style.setProperty("--fantasy-fall-color",((r=e.stageTransition)==null?void 0:r.primaryColor)||"#eee"),document.documentElement.style.setProperty("--fantasy-fall-duration",`${((s=e.stageTransition)==null?void 0:s.duration)||.6}s`),document.documentElement.style.setProperty("--fantasy-fall-delay",`${((o=e.stageTransition)==null?void 0:o.delay)||0}s`),document.documentElement.style.setProperty("--fantasy-fall-radius-sm",`${((l=(a=e.stageTransition)==null?void 0:a.borderRadius)==null?void 0:l.sm)||"14rem"}`),document.documentElement.style.setProperty("--fantasy-fall-radius-md",`${((u=(c=e.stageTransition)==null?void 0:c.borderRadius)==null?void 0:u.md)||"14rem"}`),document.documentElement.style.setProperty("--fantasy-fall-radius-lg",`${((h=(f=e.stageTransition)==null?void 0:f.borderRadius)==null?void 0:h.lg)||"50%"}`)}),(r,s)=>{var o;return mn(),vi("div",{class:Na(["fantasy-fall-transition",i.value]),style:Si({zIndex:((o=n.stageTransition)==null?void 0:o.zIndex)??100})},null,6)}}}),MH=Uo(xH,[["__scopeId","data-v-e62bf496"]]),SH=fn({__name:"MultipleBlocksRevealTransition",props:{stageTransition:null},setup(n){const e=n,t=Se(()=>e.stageTransition),i=Se(()=>{var s;return((s=t.value)==null?void 0:s.primaryColor)||"#666"}),r=Se(()=>{var s;return((s=t.value)==null?void 0:s.secondaryColor)||"#ccc"});return Hn(()=>{document.documentElement.style.setProperty("--stage-transition-4-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-4-overlay-color-2",r.value)}),(s,o)=>{var a;return mn(),vi("div",{class:"stage-transition-4",style:Si({zIndex:((a=t.value)==null?void 0:a.zIndex)??100})},o[0]||(o[0]=[DR('
',5)]),4)}}}),EH=Uo(SH,[["__scopeId","data-v-6d1179fc"]]),TH=fn({__name:"SlideTransition",props:{stageTransition:null},setup(n){const e=n,t=Se(()=>e.stageTransition),i=Se(()=>{var s;return((s=t.value)==null?void 0:s.primaryColor)||"#666"}),r=Se(()=>{var s;return((s=t.value)==null?void 0:s.secondaryColor)||"#ccc"});return Xe([t,i,r],()=>{document.documentElement.style.setProperty("--stage-transition-1-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-1-overlay-color-2",r.value)}),Hn(()=>{document.documentElement.style.setProperty("--stage-transition-1-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-1-overlay-color-2",r.value)}),(s,o)=>{var a;return mn(),vi("div",{class:"stage-transition-1",style:Si({zIndex:((a=t.value)==null?void 0:a.zIndex)??100})},null,4)}}}),wH=Uo(TH,[["__scopeId","data-v-bf1d1566"]]),AH=fn({__name:"SlopeSlideTransition",props:{stageTransition:null},setup(n){const e=n,t=Se(()=>e.stageTransition),i=Se(()=>{var s;return((s=t.value)==null?void 0:s.primaryColor)??"#666"}),r=Se(()=>{var s;return((s=t.value)==null?void 0:s.secondaryColor)??"#ccc"});return Hn(()=>{document.documentElement.style.setProperty("--stage-transition-2-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-2-overlay-color-2",r.value)}),(s,o)=>{var a;return mn(),vi("div",{class:"stage-transition-2",style:Si({zIndex:((a=t.value)==null?void 0:a.zIndex)??100})},null,4)}}}),CH=Uo(AH,[["__scopeId","data-v-8ff7120f"]]),RH=fn({__name:"RectanglesRotateTransition",props:{stageTransition:null},setup(n){const e=n;return Hn(()=>{var t,i,r,s,o,a,l;document.documentElement.style.setProperty("--rectangle-rotate-1-color",((t=e.stageTransition)==null?void 0:t.primaryColor)||"#ebcb8b"),document.documentElement.style.setProperty("--rectangle-rotate-2-color",((i=e.stageTransition)==null?void 0:i.secondaryColor)||"#c56370"),document.documentElement.style.setProperty("--rectangle-rotate-3-color",((r=e.stageTransition)==null?void 0:r.tertiaryColor)||"#43445b"),document.documentElement.style.setProperty("--rectangle-rotate-duration",`${((s=e.stageTransition)==null?void 0:s.duration)||.6}s`),document.documentElement.style.setProperty("--rectangle-rotate-delay",`${((o=e.stageTransition)==null?void 0:o.delay)||0}s`),document.documentElement.style.setProperty("--rectangle-rotate-stagger",`${((a=e.stageTransition)==null?void 0:a.staggerDelay)||.1}s`),document.documentElement.style.setProperty("--rectangle-rotate-rotation",`${((l=e.stageTransition)==null?void 0:l.rotation)||270}deg`)}),(t,i)=>{var r;return mn(),vi("div",{class:"rectangle-rotate-transition",style:Si({zIndex:((r=n.stageTransition)==null?void 0:r.zIndex)??100})},i[0]||(i[0]=[is("div",{class:"rectangle rectangle-rotate-1"},[is("div")],-1),is("div",{class:"rectangle rectangle-rotate-2"},[is("div")],-1),is("div",{class:"rectangle rectangle-rotate-3"},[is("div")],-1)]),4)}}}),PH=Uo(RH,[["__scopeId","data-v-f4b1dc64"]]),IH=fn({__name:"StageTransitionGroup",props:{primaryColor:null,secondaryColor:null,tertiaryColor:null,colors:null,zIndex:null,disableTransitions:{type:Boolean},usePageSpecificTransitions:{type:Boolean}},setup(n){const e=n,t=RV(),i=et(!1),r=et(),s=et(""),o=et(),a=De({slide:{component:wH,duration:2700},"slope-slide":{component:CH,duration:2700},arrow:{component:vH,duration:2700},"multiple-blocks-reveal":{component:EH,duration:2800},"fantasy-fall":{component:MH,duration:2700},"rectangles-rotate":{component:PH,duration:2700},"bubble-wave-out":{component:bH,duration:1e3}}),l=et([]);function c(d){return l.value.push(d),()=>{const p=l.value.indexOf(d);p>=0&&l.value.splice(p,1)}}async function u(d,p={}){r.value=d;for(const _ of l.value)try{await Promise.resolve(_(d,p))}catch(g){console.error(`Error in transition hook at stage "${d}":`,g)}}async function f(d,p,_){if(d.name==="none"||!d.name){p(),_();return}const g=a.value[d.name];if(!g){console.error(`Transition ${d.name} not found`),p(),_();return}const m=g.nextDelay!==void 0?g.nextDelay:g.duration/3;let y=!1;const v=c(E=>{E==="navigation"&&!y&&(y=!0,p())});try{await u("before-enter",{transitionName:d.name}),i.value&&(await u("before-leave",{transitionName:s.value}),s.value="",o.value=void 0,i.value=!1,await u("after-leave",{transitionName:s.value}),await new Promise(T=>setTimeout(T,50))),s.value=d.name,o.value=d,i.value=!0,await u("enter-active",{transitionName:name}),setTimeout(async()=>{await u("navigation",{transitionName:d.name,config:g}),y||(y=!0,p())},m),setTimeout(async()=>{await u("after-enter",{transitionName:d.name})},g.duration),setTimeout(async()=>{await u("before-leave",{transitionName:d.name})},g.duration+10),setTimeout(async()=>{await u("leave-active",{transitionName:d.name})},g.duration+20);const E=g.exitDuration??0;setTimeout(async()=>{i.value=!1,s.value="",o.value=void 0,await u("after-leave",{transitionName:d.name}),_()},g.duration+E)}catch(E){console.error(E)}finally{v(),setTimeout(()=>{y||(y=!0,p())},g.duration*2)}}function h(d,p){return new Promise(_=>{f(d,p,_)})}return t.beforeEach((d,p,_)=>{if(e.disableTransitions){_();return}if(typeof d.meta.stageTransition!="object"){_();return}const g=d.meta.stageTransition;if(e.usePageSpecificTransitions&&g.pageSpecificAvailable){_();return}typeof e.primaryColor<"u"&&(g.primaryColor=e.primaryColor),typeof e.secondaryColor<"u"&&(g.secondaryColor=e.secondaryColor),typeof e.tertiaryColor<"u"&&(g.tertiaryColor=e.tertiaryColor),typeof e.colors<"u"&&(g.colors=e.colors),typeof e.zIndex<"u"&&(g.zIndex=e.zIndex),h(g,_)}),(d,p)=>(mn(),vi(jt,null,[tR(d.$slots,"default"),i.value?(mn(),vi(jt,{key:0},[a.value[s.value]?(mn(),Yl(QC(a.value[s.value].component),{key:0,"stage-transition":o.value},null,8,["stage-transition"])):Cv("",!0)],64)):Cv("",!0)],64))}});/*! diff --git a/assets/index-BNrxdvv8.js b/assets/index-Rz4v4VGO.js similarity index 94% rename from assets/index-BNrxdvv8.js rename to assets/index-Rz4v4VGO.js index 38210569f5ed74607e10207bd5845d207d41fb50..44dbf9f14a2e578d03ef42eff14204e59a7c0b46 100644 --- a/assets/index-BNrxdvv8.js +++ b/assets/index-Rz4v4VGO.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as S,r as A,x as y,o as r,y as D,a as e,c as g,C as h,p as P,D as k,z as R,bn as L,bE as N,g as l,i as V,v as q,h as F,bw as O,A as x,e as m,bx as $,by as j,n as G,bv as H}from"./index-rD0Uu1v9.js";import{_ as J}from"./IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js";import{b as I}from"./route-block-B_A1xBdJ.js";const K={"z-1":"","flex-1":""},M={"text-lg":"","font-bold":"",class:"menu-icon-item-title",transition:"all ease-in-out duration-400"},Q={text:"sm neutral-500 dark:neutral-400",class:"menu-icon-item-description",transition:"all ease-in-out duration-400"},U=S({__name:"IconItem",props:{title:null,description:null,icon:null,iconTemplate:{type:Boolean},to:null},setup(i){return(c,v)=>{const f=A("RouterLink");return r(),y(f,{box:"border",flex:"~ row",bg:"neutral-50 dark:neutral-800",border:"neutral-100 dark:neutral-700 hover:primary-500/30 dark:hover:primary-400/30 solid 2","drop-shadow":"none hover:[0px_4px_4px_rgba(220,220,220,0.4)] active:[0px_0px_0px_rgba(220,220,220,0.25)] dark:hover:none",class:"menu-icon-item",transition:"all ease-in-out duration-400",relative:"","w-full":"","items-center":"","overflow-hidden":"","rounded-lg":"","p-5":"","text-left":"",cursor:"pointer",to:i.to},{default:D(()=>[e("div",K,[e("div",M,k(i.title),1),e("div",Q,[e("span",null,k(i.description),1)])]),typeof i.icon=="string"?(r(),g("div",{key:0,class:R(["menu-icon-item-icon",[i.icon]]),transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-24":"","translate-y-4":"",text:"neutral-400/50 dark:neutral-600/50"},null,2)):h("",!0),i.iconTemplate?P(c.$slots,"icon",{key:1},void 0,!0):h("",!0)]),_:3},8,["to"])}}}),W=L(U,[["__scopeId","data-v-a1ec902c"]]),X={flex:"","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},duration:100},Y={"text-3xl":""},Z={flex:"~ col gap-4"},tt={flex:"~ col gap-4"},et={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},nt={text:"60","i-lucide:cog":""},it=S({__name:"index",setup(i){const c=N(),v=l(!1),f=l(),d=l(),{t:n}=V(),b=l(""),w=l(""),C=l(!1),u=q();function T(){var o;(o=d.value)==null||o.call(d)}async function z(o,s){const t=o.currentTarget.querySelector(".menu-icon-item-icon");if(!t)return;const p=t.getBoundingClientRect(),_=`${p.left}px, ${p.top}px`;b.value=s.icon,w.value=_,C.value=!0,await H(),v.value=!0}const B=c.beforeEach(async(o,s,a)=>{if(!u.usePageSpecificTransitions||u.disableTransitions){a();return}await new Promise(t=>{d.value=t}),B(),a()}),E=F(()=>[{title:n("settings.pages.modules.title"),description:n("settings.pages.modules.description"),icon:"i-lucide:blocks",to:"/settings/modules"},{title:n("settings.pages.models.title"),description:n("settings.pages.models.description"),icon:"i-lucide:person-standing",to:"/settings/models"},{title:n("settings.pages.memory.title"),description:n("settings.pages.memory.description"),icon:"i-lucide:sprout",to:"/settings/memory"},{title:n("settings.pages.providers.title"),description:n("settings.pages.providers.description"),icon:"i-lucide:brain",to:"/settings/providers"},{title:n("settings.pages.themes.title"),description:n("settings.pages.themes.description"),icon:"i-lucide:paintbrush",to:"/settings/appearance"}]);return(o,s)=>{const a=O("motion");return r(),g($,null,[x((r(),g("div",X,[e("button",{onClick:s[0]||(s[0]=t=>m(c).back())},s[1]||(s[1]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),e("h1",Y,k(o.$t("settings.title")),1)])),[[a]]),e("div",Z,[e("div",tt,[(r(!0),g($,null,j(E.value,(t,p)=>x((r(),y(m(W),{key:t.to,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250,style:G({transitionDelay:`${p*50}ms`}),title:t.title,description:t.description,icon:t.icon,to:t.to,onClick:_=>z(_,t)},null,8,["style","title","description","icon","to","onClick"])),[[a]])),128))]),e("div",et,[x(e("div",nt,null,512),[[a]])]),C.value&&!m(u).disableTransitions&&m(u).usePageSpecificTransitions?(r(),y(J,{key:0,ref_key:"iconAnimation",ref:f,icon:b.value,"icon-size":6*1.2,position:w.value,duration:1e3,"text-color":"text-neutral-400/50 dark:text-neutral-600/20",started:v.value,onAnimationEndedOnce:T},null,8,["icon","position","started"])):h("",!0)])],64)}}});typeof I=="function"&&I(it);export{it as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as S,r as A,x as y,o as r,y as D,a as e,c as g,C as h,p as P,D as k,z as R,bn as L,bE as N,g as l,i as V,v as q,h as F,bw as O,A as x,e as m,bx as $,by as j,n as G,bv as H}from"./index-Dlp4W1Zl.js";import{_ as J}from"./IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js";import{b as I}from"./route-block-B_A1xBdJ.js";const K={"z-1":"","flex-1":""},M={"text-lg":"","font-bold":"",class:"menu-icon-item-title",transition:"all ease-in-out duration-400"},Q={text:"sm neutral-500 dark:neutral-400",class:"menu-icon-item-description",transition:"all ease-in-out duration-400"},U=S({__name:"IconItem",props:{title:null,description:null,icon:null,iconTemplate:{type:Boolean},to:null},setup(i){return(c,v)=>{const f=A("RouterLink");return r(),y(f,{box:"border",flex:"~ row",bg:"neutral-50 dark:neutral-800",border:"neutral-100 dark:neutral-700 hover:primary-500/30 dark:hover:primary-400/30 solid 2","drop-shadow":"none hover:[0px_4px_4px_rgba(220,220,220,0.4)] active:[0px_0px_0px_rgba(220,220,220,0.25)] dark:hover:none",class:"menu-icon-item",transition:"all ease-in-out duration-400",relative:"","w-full":"","items-center":"","overflow-hidden":"","rounded-lg":"","p-5":"","text-left":"",cursor:"pointer",to:i.to},{default:D(()=>[e("div",K,[e("div",M,k(i.title),1),e("div",Q,[e("span",null,k(i.description),1)])]),typeof i.icon=="string"?(r(),g("div",{key:0,class:R(["menu-icon-item-icon",[i.icon]]),transition:"all ease-in-out duration-400",absolute:"","right-0":"","size-24":"","translate-y-4":"",text:"neutral-400/50 dark:neutral-600/50"},null,2)):h("",!0),i.iconTemplate?P(c.$slots,"icon",{key:1},void 0,!0):h("",!0)]),_:3},8,["to"])}}}),W=L(U,[["__scopeId","data-v-a1ec902c"]]),X={flex:"","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},duration:100},Y={"text-3xl":""},Z={flex:"~ col gap-4"},tt={flex:"~ col gap-4"},et={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},nt={text:"60","i-lucide:cog":""},it=S({__name:"index",setup(i){const c=N(),v=l(!1),f=l(),d=l(),{t:n}=V(),b=l(""),w=l(""),C=l(!1),u=q();function T(){var o;(o=d.value)==null||o.call(d)}async function z(o,s){const t=o.currentTarget.querySelector(".menu-icon-item-icon");if(!t)return;const p=t.getBoundingClientRect(),_=`${p.left}px, ${p.top}px`;b.value=s.icon,w.value=_,C.value=!0,await H(),v.value=!0}const B=c.beforeEach(async(o,s,a)=>{if(!u.usePageSpecificTransitions||u.disableTransitions){a();return}await new Promise(t=>{d.value=t}),B(),a()}),E=F(()=>[{title:n("settings.pages.modules.title"),description:n("settings.pages.modules.description"),icon:"i-lucide:blocks",to:"/settings/modules"},{title:n("settings.pages.models.title"),description:n("settings.pages.models.description"),icon:"i-lucide:person-standing",to:"/settings/models"},{title:n("settings.pages.memory.title"),description:n("settings.pages.memory.description"),icon:"i-lucide:sprout",to:"/settings/memory"},{title:n("settings.pages.providers.title"),description:n("settings.pages.providers.description"),icon:"i-lucide:brain",to:"/settings/providers"},{title:n("settings.pages.themes.title"),description:n("settings.pages.themes.description"),icon:"i-lucide:paintbrush",to:"/settings/appearance"}]);return(o,s)=>{const a=O("motion");return r(),g($,null,[x((r(),g("div",X,[e("button",{onClick:s[0]||(s[0]=t=>m(c).back())},s[1]||(s[1]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),e("h1",Y,k(o.$t("settings.title")),1)])),[[a]]),e("div",Z,[e("div",tt,[(r(!0),g($,null,j(E.value,(t,p)=>x((r(),y(m(W),{key:t.to,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250,style:G({transitionDelay:`${p*50}ms`}),title:t.title,description:t.description,icon:t.icon,to:t.to,onClick:_=>z(_,t)},null,8,["style","title","description","icon","to","onClick"])),[[a]])),128))]),e("div",et,[x(e("div",nt,null,512),[[a]])]),C.value&&!m(u).disableTransitions&&m(u).usePageSpecificTransitions?(r(),y(J,{key:0,ref_key:"iconAnimation",ref:f,icon:b.value,"icon-size":6*1.2,position:w.value,duration:1e3,"text-color":"text-neutral-400/50 dark:text-neutral-600/20",started:v.value,onAnimationEndedOnce:T},null,8,["icon","position","started"])):h("",!0)])],64)}}});typeof I=="function"&&I(it);export{it as default}; diff --git a/assets/index-0_JGTbws.js b/assets/index-YJa3XIzO.js similarity index 99% rename from assets/index-0_JGTbws.js rename to assets/index-YJa3XIzO.js index b991292fb4f95e1281d351aaa4614479240dbf9e..86840f52acbffc7bcf8bc41895c3f65cc135e802 100644 --- a/assets/index-0_JGTbws.js +++ b/assets/index-YJa3XIzO.js @@ -1,4 +1,4 @@ -import{cr as getAugmentedNamespace}from"./index-rD0Uu1v9.js";var dist={},ortWeb_min={exports:{}};const backends={},backendsSortedByPriority=[],registerBackend=(D,u,b)=>{if(u&&typeof u.init=="function"&&typeof u.createSessionHandler=="function"){const g=backends[D];if(g===void 0)backends[D]={backend:u,priority:b};else{if(g.priority>b)return;if(g.priority===b&&g.backend!==u)throw new Error(`cannot register backend "${D}" using priority ${b}`)}if(b>=0){const p=backendsSortedByPriority.indexOf(D);p!==-1&&backendsSortedByPriority.splice(p,1);for(let h=0;h{const u=D.length===0?backendsSortedByPriority:D,b=[];for(const g of u){const p=backends[g];if(p){if(p.initialized)return p.backend;if(p.aborted)continue;const h=!!p.initPromise;try{return h||(p.initPromise=p.backend.init()),await p.initPromise,p.initialized=!0,p.backend}catch(o){h||b.push({name:g,err:o}),p.aborted=!0}finally{delete p.initPromise}}}throw new Error(`no available backend found. ERR: ${b.map(g=>`[${g.name}] ${g.err}`).join(", ")}`)};class EnvImpl{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(u){if(u!==void 0){if(typeof u!="string"||["verbose","info","warning","error","fatal"].indexOf(u)===-1)throw new Error(`Unsupported logging level: ${u}`);this.logLevelInternal=u}}get logLevel(){return this.logLevelInternal}}const env=new EnvImpl,isBigInt64ArrayAvailable=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",isBigUint64ArrayAvailable=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function",NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);isBigInt64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64"));isBigUint64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"));const calculateSize=D=>{let u=1;for(let b=0;b{const t=document.createElement("canvas"),e=t.getContext("2d");if(!u||!e)return i();const n=new Image;n.crossOrigin="Anonymous",n.src=u,n.onload=()=>{t.width=n.width,t.height=n.height,e.drawImage(n,0,0,t.width,t.height);const r=e.getImageData(0,0,t.width,t.height);if(b!==void 0){if(b.height!==void 0&&b.height!==t.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(f.height=t.height,b.width!==void 0&&b.width!==t.width)throw new Error("Image input config width doesn't match ImageBitmap width");f.width=t.width}else f.height=t.height,f.width=t.width;s(at.bufferToTensor(r.data,f))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(c!==void 0)return at.bufferToTensor(c,f);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(u){var b,g;const p=document.createElement("canvas").getContext("2d");let h;if(p!=null){const o=this.dims[3],c=this.dims[2],f=this.dims[1],s=u!==void 0&&u.format!==void 0?u.format:"RGB",i=u!==void 0&&((b=u.norm)===null||b===void 0?void 0:b.mean)!==void 0?u.norm.mean:255,t=u!==void 0&&((g=u.norm)===null||g===void 0?void 0:g.bias)!==void 0?u.norm.bias:0,e=c*o;if(u!==void 0){if(u.height!==void 0&&u.height!==c)throw new Error("Image output config height doesn't match tensor height");if(u.width!==void 0&&u.width!==o)throw new Error("Image output config width doesn't match tensor width");if(u.format!==void 0&&f===4&&u.format!=="RGBA"||f===3&&u.format!=="RGB"&&u.format!=="BGR")throw new Error("Tensor format doesn't match input tensor dims")}const n=4;let r=0,a=1,l=2,d=3,m=0,y=e,v=e*2,_=-1;s==="RGBA"?(m=0,y=e,v=e*2,_=e*3):s==="RGB"?(m=0,y=e,v=e*2):s==="RBG"&&(m=0,v=e,y=e*2),h=p.createImageData(o,c);for(let T=0;T"u")throw new Error(`input '${s}' is missing in 'feeds'.`);if(o)for(const s of this.outputNames)p[s]=null;const c=await this.handler.run(u,p,h),f={};for(const s in c)Object.hasOwnProperty.call(c,s)&&(f[s]=new Tensor(c[s].type,c[s].data,c[s].dims));return f}static async create(u,b,g,p){let h,o={};if(typeof u=="string"){if(h=u,typeof b=="object"&&b!==null)o=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof Uint8Array){if(h=u,typeof b=="object"&&b!==null)o=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&u instanceof SharedArrayBuffer){const t=u;let e=0,n=u.byteLength;if(typeof b=="object"&&b!==null)o=b;else if(typeof b=="number"){if(e=b,!Number.isSafeInteger(e))throw new RangeError("'byteOffset' must be an integer.");if(e<0||e>=t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${t.byteLength}).`);if(n=u.byteLength-e,typeof g=="number"){if(n=g,!Number.isSafeInteger(n))throw new RangeError("'byteLength' must be an integer.");if(n<=0||e+n>t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${t.byteLength-e}].`);if(typeof p=="object"&&p!==null)o=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(typeof g<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof b<"u")throw new TypeError("'options' must be an object.");h=new Uint8Array(t,e,n)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const f=(o.executionProviders||[]).map(t=>typeof t=="string"?t:t.name),i=await(await resolveBackend(f)).createSessionHandler(h,o);return new cn(i)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const InferenceSession=InferenceSession$1,lib=Object.freeze(Object.defineProperty({__proto__:null,InferenceSession,Tensor,env,registerBackend},Symbol.toStringTag,{value:"Module"})),require$$0=getAugmentedNamespace(lib);/*! +import{cr as getAugmentedNamespace}from"./index-Dlp4W1Zl.js";var dist={},ortWeb_min={exports:{}};const backends={},backendsSortedByPriority=[],registerBackend=(D,u,b)=>{if(u&&typeof u.init=="function"&&typeof u.createSessionHandler=="function"){const g=backends[D];if(g===void 0)backends[D]={backend:u,priority:b};else{if(g.priority>b)return;if(g.priority===b&&g.backend!==u)throw new Error(`cannot register backend "${D}" using priority ${b}`)}if(b>=0){const p=backendsSortedByPriority.indexOf(D);p!==-1&&backendsSortedByPriority.splice(p,1);for(let h=0;h{const u=D.length===0?backendsSortedByPriority:D,b=[];for(const g of u){const p=backends[g];if(p){if(p.initialized)return p.backend;if(p.aborted)continue;const h=!!p.initPromise;try{return h||(p.initPromise=p.backend.init()),await p.initPromise,p.initialized=!0,p.backend}catch(o){h||b.push({name:g,err:o}),p.aborted=!0}finally{delete p.initPromise}}}throw new Error(`no available backend found. ERR: ${b.map(g=>`[${g.name}] ${g.err}`).join(", ")}`)};class EnvImpl{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(u){if(u!==void 0){if(typeof u!="string"||["verbose","info","warning","error","fatal"].indexOf(u)===-1)throw new Error(`Unsupported logging level: ${u}`);this.logLevelInternal=u}}get logLevel(){return this.logLevelInternal}}const env=new EnvImpl,isBigInt64ArrayAvailable=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",isBigUint64ArrayAvailable=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function",NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);isBigInt64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64"));isBigUint64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"));const calculateSize=D=>{let u=1;for(let b=0;b{const t=document.createElement("canvas"),e=t.getContext("2d");if(!u||!e)return i();const n=new Image;n.crossOrigin="Anonymous",n.src=u,n.onload=()=>{t.width=n.width,t.height=n.height,e.drawImage(n,0,0,t.width,t.height);const r=e.getImageData(0,0,t.width,t.height);if(b!==void 0){if(b.height!==void 0&&b.height!==t.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(f.height=t.height,b.width!==void 0&&b.width!==t.width)throw new Error("Image input config width doesn't match ImageBitmap width");f.width=t.width}else f.height=t.height,f.width=t.width;s(at.bufferToTensor(r.data,f))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(c!==void 0)return at.bufferToTensor(c,f);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(u){var b,g;const p=document.createElement("canvas").getContext("2d");let h;if(p!=null){const o=this.dims[3],c=this.dims[2],f=this.dims[1],s=u!==void 0&&u.format!==void 0?u.format:"RGB",i=u!==void 0&&((b=u.norm)===null||b===void 0?void 0:b.mean)!==void 0?u.norm.mean:255,t=u!==void 0&&((g=u.norm)===null||g===void 0?void 0:g.bias)!==void 0?u.norm.bias:0,e=c*o;if(u!==void 0){if(u.height!==void 0&&u.height!==c)throw new Error("Image output config height doesn't match tensor height");if(u.width!==void 0&&u.width!==o)throw new Error("Image output config width doesn't match tensor width");if(u.format!==void 0&&f===4&&u.format!=="RGBA"||f===3&&u.format!=="RGB"&&u.format!=="BGR")throw new Error("Tensor format doesn't match input tensor dims")}const n=4;let r=0,a=1,l=2,d=3,m=0,y=e,v=e*2,_=-1;s==="RGBA"?(m=0,y=e,v=e*2,_=e*3):s==="RGB"?(m=0,y=e,v=e*2):s==="RBG"&&(m=0,v=e,y=e*2),h=p.createImageData(o,c);for(let T=0;T"u")throw new Error(`input '${s}' is missing in 'feeds'.`);if(o)for(const s of this.outputNames)p[s]=null;const c=await this.handler.run(u,p,h),f={};for(const s in c)Object.hasOwnProperty.call(c,s)&&(f[s]=new Tensor(c[s].type,c[s].data,c[s].dims));return f}static async create(u,b,g,p){let h,o={};if(typeof u=="string"){if(h=u,typeof b=="object"&&b!==null)o=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof Uint8Array){if(h=u,typeof b=="object"&&b!==null)o=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&u instanceof SharedArrayBuffer){const t=u;let e=0,n=u.byteLength;if(typeof b=="object"&&b!==null)o=b;else if(typeof b=="number"){if(e=b,!Number.isSafeInteger(e))throw new RangeError("'byteOffset' must be an integer.");if(e<0||e>=t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${t.byteLength}).`);if(n=u.byteLength-e,typeof g=="number"){if(n=g,!Number.isSafeInteger(n))throw new RangeError("'byteLength' must be an integer.");if(n<=0||e+n>t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${t.byteLength-e}].`);if(typeof p=="object"&&p!==null)o=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(typeof g<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof b<"u")throw new TypeError("'options' must be an object.");h=new Uint8Array(t,e,n)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const f=(o.executionProviders||[]).map(t=>typeof t=="string"?t:t.name),i=await(await resolveBackend(f)).createSessionHandler(h,o);return new cn(i)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const InferenceSession=InferenceSession$1,lib=Object.freeze(Object.defineProperty({__proto__:null,InferenceSession,Tensor,env,registerBackend},Symbol.toStringTag,{value:"Module"})),require$$0=getAugmentedNamespace(lib);/*! * ONNX Runtime Web v1.14.0 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. diff --git a/assets/index-DEIl8OlI.js b/assets/index-ebWEHfej.js similarity index 95% rename from assets/index-DEIl8OlI.js rename to assets/index-ebWEHfej.js index cdabfaa818e94cbb093b97f33c0be1b614926a62..7b63d8961d9a144e99b4eb134f9bc6e89fb6ffa5 100644 --- a/assets/index-DEIl8OlI.js +++ b/assets/index-ebWEHfej.js @@ -1 +1 @@ -import{_ as z}from"./IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js";import{d as D,bF as I,bG as M,c as d,o as r,A as c,a as e,b as l,B as A,bH as v,C as h,D as a,bB as O,y as g,z as C,bE as P,v as N,bC as R,g as L,w as j,bw as G,x as J,e as n,ad as q,bI as K,bJ as Q,bx as B,by as W,bn as X}from"./index-rD0Uu1v9.js";import"./live2d-zip-loader-BdiFCiUD.js";import{_ as f,a as Y}from"./Section.vue_vue_type_script_setup_true_lang-BtOV76U1.js";import{u as Z}from"./useIconAnimation-BDdHp70p.js";import{b as k}from"./route-block-B_A1xBdJ.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";const ee={class:"setting-bar cursor-pointer text-sm",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},te=["aria-checked"],ne={key:0,text:"sm neutral-500"},y=D({__name:"CheckBar",props:I({text:null,iconOn:null,iconOff:null,description:null},{modelValue:{type:Boolean},modelModifiers:{}}),emits:["update:modelValue"],setup(u){const p=M(u,"modelValue");return(s,m)=>(r(),d("label",ee,[c(e("input",{"onUpdate:modelValue":m[0]||(m[0]=b=>p.value=b),"aria-checked":p.value,type:"checkbox",hidden:""},null,8,te),[[A,p.value]]),e("div",null,[v(a(s.$t(u.text))+" ",1),u.description?(r(),d("div",ne,a(s.$t(u.description)),1)):h("",!0)]),l(O,{name:"slide-away",mode:"out-in"},{default:g(()=>[p.value?(r(),d("div",{key:0,class:C(u.iconOn),transition:"all ease-in-out duration-250"},null,2)):(r(),d("div",{key:1,class:C(u.iconOff),transition:"all ease-in-out duration-250"},null,2))]),_:1})]))}}),se=[[],["#A5978B","#D8CAAF","#B8B4A7","#C4BCB1","#E5DED8","#9A8F7D","#BEB5A7","#C9C0B6"],["#7A9EAF","#B8C7CC","#D4B79C","#8B9D77","#C7D5CB","#E6D0B1","#94A7B1","#B4C8C3"],["#D9B48F","#B5917A","#8C7A6B","#A17F5F","#B98C46","#C7A252","#DAB300","#D19826"],["#9BA7B0","#C1CBD4","#A5ADB6","#8B959E","#D4DCE4","#7F8A94","#B3BCC6","#98A4AE"],["#E4C6D0","#A61B29","#5D513C","#789262","#1C0D1A","#F7C242","#62A9DD","#8C4B3C"]],oe={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},ie={relative:""},ae={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},re={text:"neutral-300 dark:neutral-500","text-nowrap":""},le={"text-nowrap":"","text-3xl":"","font-semibold":""},de={class:"setting-bar text-sm",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},ue={value:"en-US"},pe={value:"zh-CN"},me={flex:"","items-center":"","justify-between":""},ce={"text-lg":"","font-semibold":""},ge={relative:"",flex:"","cursor-pointer":"","items-center":"","gap-2":""},be=["disabled"],fe={"font-medium":""},ye={text:"sm neutral-500"},ve={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},_=D({__name:"index",setup(u){const p=P(),s=N(),m=R(),b=L(!1),{iconAnimationStarted:$,showIconAnimation:V,animationIcon:w}=Z("i-lucide:paintbrush");return j(()=>[s.usePageSpecificTransitions,s.disableTransitions],()=>{b.value=!0}),(i,t)=>{const E=z,S=G("motion");return r(),d(B,null,[c((r(),d("div",oe,[e("button",{onClick:t[0]||(t[0]=o=>n(p).back())},t[7]||(t[7]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),e("h1",ie,[e("div",ae,[e("span",re,a(i.$t("settings.title")),1)]),e("div",le,a(i.$t("settings.pages.themes.title")),1)])])),[[S]]),l(f,{title:"settings.sections.section.general.title",icon:"i-solar:filters-bold-duotone"},{default:g(()=>[l(y,{modelValue:n(m),"onUpdate:modelValue":t[1]||(t[1]=o=>q(m)?m.value=o:null),"icon-on":"i-solar:moon-stars-bold-duotone","icon-off":"i-solar:sun-fog-bold-duotone",text:"settings.theme"},null,8,["modelValue"]),e("div",de,[v(a(i.$t("settings.language.title"))+" ",1),c(e("select",{"onUpdate:modelValue":t[2]||(t[2]=o=>n(s).language=o),transition:"all ease-in-out duration-250","cursor-pointer":"","bg-transparent":"","text-right":"","outline-none":""},[e("option",ue,a(i.$t("settings.language.english")),1),e("option",pe,a(i.$t("settings.language.chinese")),1)],512),[[K,n(s).language]])])]),_:1}),l(f,{title:"settings.pages.themes.sections.section.custom-color.title",icon:"i-solar:pallete-2-bold-duotone"},{default:g(()=>[e("div",me,[e("span",ce,a(i.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.label")),1),e("label",ge,[c(e("input",{"onUpdate:modelValue":t[3]||(t[3]=o=>n(s).themeColorsHueDynamic=o),type:"checkbox",class:"peer sr-only"},null,512),[[A,n(s).themeColorsHueDynamic]]),t[8]||(t[8]=e("div",{class:"peer-checked:bg-primary-500 h-6 w-11 rounded-full bg-neutral-200 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white dark:bg-neutral-600 after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white"},null,-1)),v(" "+a(i.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.rgb-on.title")),1)])]),c(e("input",{"onUpdate:modelValue":t[4]||(t[4]=o=>n(s).themeColorsHue=o),type:"range",min:"0",max:"360",step:"0.01",class:C(["theme-hue-slider",n(s).themeColorsHueDynamic?"opacity-25 cursor-not-allowed":"cursor-pointer"]),disabled:n(s).themeColorsHueDynamic},null,10,be),[[Q,n(s).themeColorsHue]]),t[9]||(t[9]=e("div",{class:"color-bar"},[e("span",{"bg-primary-50":""},"50"),e("span",{"bg-primary-100":""},"100"),e("span",{"bg-primary-200":""},"200"),e("span",{"bg-primary-300":""},"300"),e("span",{"bg-primary-400":""},"400"),e("span",{"bg-primary-500":""},"500"),e("div",{"text-white":""},[e("span",{"bg-primary-600":""},"600"),e("span",{"bg-primary-700":""},"700"),e("span",{"bg-primary-800":""},"800"),e("span",{"bg-primary-900":""},"900"),e("span",{"bg-primary-950":""},"950")])],-1)),t[10]||(t[10]=e("div",{class:"color-bar transparency-grid"},[e("span",{bg:"primary-500/5"},"500/5"),e("span",{bg:"primary-500/10"},"500/10"),e("span",{bg:"primary-500/20"},"500/20"),e("span",{bg:"primary-500/30"},"500/30"),e("span",{bg:"primary-500/40"},"500/40"),e("span",{bg:"primary-500/50"},"500/50"),e("span",{bg:"primary-500/60"},"500/60"),e("span",{bg:"primary-500/70"},"500/70"),e("span",{bg:"primary-500/80"},"500/80"),e("span",{bg:"primary-500/90"},"500/90"),e("span",{bg:"primary-500"},"500")],-1))]),_:1}),l(f,{title:"settings.pages.themes.sections.section.theme-presets.title",icon:"i-solar:magic-stick-2-bold-duotone"},{default:g(()=>[(r(!0),d(B,null,W(i.$tm("settings.pages.themes.sections.section.theme-presets.presets"),({title:o,description:T,colors:F},x)=>(r(),d("div",{key:x,class:"setting-bar",bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},[e("div",null,[e("span",fe,a(i.$rt(o)),1),e("div",ye,a(i.$rt(T)),1)]),l(Y,{colors:F.map((U,H)=>({hex:n(se)[x][H],name:i.$rt(U)}))},null,8,["colors"])]))),128))]),_:1}),l(f,{title:"settings.pages.themes.sections.section.developer.title",icon:"i-solar:code-bold-duotone"},{default:g(()=>[l(y,{modelValue:n(s).disableTransitions,"onUpdate:modelValue":t[5]||(t[5]=o=>n(s).disableTransitions=o),"icon-on":"i-solar:people-nearby-bold-duotone","icon-off":"i-solar:running-2-line-duotone",text:"settings.animations.stage-transitions.title"},null,8,["modelValue"]),l(y,{modelValue:n(s).usePageSpecificTransitions,"onUpdate:modelValue":t[6]||(t[6]=o=>n(s).usePageSpecificTransitions=o),disabled:n(s).disableTransitions,"icon-on":"i-solar:running-2-line-duotone","icon-off":"i-solar:people-nearby-bold-duotone",text:"settings.animations.use-page-specific-transitions.title",description:"settings.animations.use-page-specific-transitions.description"},null,8,["modelValue","disabled"])]),_:1}),n(V)&&!b.value?(r(),J(E,{key:0,"z-index":-1,duration:1e3,started:n($),"is-reverse":!0,icon:n(w),"icon-size":12,position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)","text-color":"text-neutral-200/50 dark:text-neutral-600/20"},null,8,["started","icon"])):h("",!0),n(s).usePageSpecificTransitions?h("",!0):(r(),d("div",ve,t[11]||(t[11]=[e("div",{text:"40","i-lucide:paintbrush":""},null,-1)])))],64)}}});typeof k=="function"&&k(_);const $e=X(_,[["__scopeId","data-v-1285983e"]]);export{$e as default}; +import{_ as z}from"./IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js";import{d as D,bF as I,bG as M,c as d,o as r,A as c,a as e,b as l,B as A,bH as v,C as h,D as a,bB as O,y as g,z as C,bE as P,v as N,bC as R,g as L,w as j,bw as G,x as J,e as n,ad as q,bI as K,bJ as Q,bx as B,by as W,bn as X}from"./index-Dlp4W1Zl.js";import"./live2d-zip-loader-C5j9stxV.js";import{_ as f,a as Y}from"./Section.vue_vue_type_script_setup_true_lang-Ju8FFDso.js";import{u as Z}from"./useIconAnimation-DMJpspm5.js";import{b as k}from"./route-block-B_A1xBdJ.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";const ee={class:"setting-bar cursor-pointer text-sm",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},te=["aria-checked"],ne={key:0,text:"sm neutral-500"},y=D({__name:"CheckBar",props:I({text:null,iconOn:null,iconOff:null,description:null},{modelValue:{type:Boolean},modelModifiers:{}}),emits:["update:modelValue"],setup(u){const p=M(u,"modelValue");return(s,m)=>(r(),d("label",ee,[c(e("input",{"onUpdate:modelValue":m[0]||(m[0]=b=>p.value=b),"aria-checked":p.value,type:"checkbox",hidden:""},null,8,te),[[A,p.value]]),e("div",null,[v(a(s.$t(u.text))+" ",1),u.description?(r(),d("div",ne,a(s.$t(u.description)),1)):h("",!0)]),l(O,{name:"slide-away",mode:"out-in"},{default:g(()=>[p.value?(r(),d("div",{key:0,class:C(u.iconOn),transition:"all ease-in-out duration-250"},null,2)):(r(),d("div",{key:1,class:C(u.iconOff),transition:"all ease-in-out duration-250"},null,2))]),_:1})]))}}),se=[[],["#A5978B","#D8CAAF","#B8B4A7","#C4BCB1","#E5DED8","#9A8F7D","#BEB5A7","#C9C0B6"],["#7A9EAF","#B8C7CC","#D4B79C","#8B9D77","#C7D5CB","#E6D0B1","#94A7B1","#B4C8C3"],["#D9B48F","#B5917A","#8C7A6B","#A17F5F","#B98C46","#C7A252","#DAB300","#D19826"],["#9BA7B0","#C1CBD4","#A5ADB6","#8B959E","#D4DCE4","#7F8A94","#B3BCC6","#98A4AE"],["#E4C6D0","#A61B29","#5D513C","#789262","#1C0D1A","#F7C242","#62A9DD","#8C4B3C"]],oe={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},ie={relative:""},ae={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},re={text:"neutral-300 dark:neutral-500","text-nowrap":""},le={"text-nowrap":"","text-3xl":"","font-semibold":""},de={class:"setting-bar text-sm",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},ue={value:"en-US"},pe={value:"zh-CN"},me={flex:"","items-center":"","justify-between":""},ce={"text-lg":"","font-semibold":""},ge={relative:"",flex:"","cursor-pointer":"","items-center":"","gap-2":""},be=["disabled"],fe={"font-medium":""},ye={text:"sm neutral-500"},ve={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},_=D({__name:"index",setup(u){const p=P(),s=N(),m=R(),b=L(!1),{iconAnimationStarted:$,showIconAnimation:V,animationIcon:w}=Z("i-lucide:paintbrush");return j(()=>[s.usePageSpecificTransitions,s.disableTransitions],()=>{b.value=!0}),(i,t)=>{const E=z,S=G("motion");return r(),d(B,null,[c((r(),d("div",oe,[e("button",{onClick:t[0]||(t[0]=o=>n(p).back())},t[7]||(t[7]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),e("h1",ie,[e("div",ae,[e("span",re,a(i.$t("settings.title")),1)]),e("div",le,a(i.$t("settings.pages.themes.title")),1)])])),[[S]]),l(f,{title:"settings.sections.section.general.title",icon:"i-solar:filters-bold-duotone"},{default:g(()=>[l(y,{modelValue:n(m),"onUpdate:modelValue":t[1]||(t[1]=o=>q(m)?m.value=o:null),"icon-on":"i-solar:moon-stars-bold-duotone","icon-off":"i-solar:sun-fog-bold-duotone",text:"settings.theme"},null,8,["modelValue"]),e("div",de,[v(a(i.$t("settings.language.title"))+" ",1),c(e("select",{"onUpdate:modelValue":t[2]||(t[2]=o=>n(s).language=o),transition:"all ease-in-out duration-250","cursor-pointer":"","bg-transparent":"","text-right":"","outline-none":""},[e("option",ue,a(i.$t("settings.language.english")),1),e("option",pe,a(i.$t("settings.language.chinese")),1)],512),[[K,n(s).language]])])]),_:1}),l(f,{title:"settings.pages.themes.sections.section.custom-color.title",icon:"i-solar:pallete-2-bold-duotone"},{default:g(()=>[e("div",me,[e("span",ce,a(i.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.label")),1),e("label",ge,[c(e("input",{"onUpdate:modelValue":t[3]||(t[3]=o=>n(s).themeColorsHueDynamic=o),type:"checkbox",class:"peer sr-only"},null,512),[[A,n(s).themeColorsHueDynamic]]),t[8]||(t[8]=e("div",{class:"peer-checked:bg-primary-500 h-6 w-11 rounded-full bg-neutral-200 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white dark:bg-neutral-600 after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white"},null,-1)),v(" "+a(i.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.rgb-on.title")),1)])]),c(e("input",{"onUpdate:modelValue":t[4]||(t[4]=o=>n(s).themeColorsHue=o),type:"range",min:"0",max:"360",step:"0.01",class:C(["theme-hue-slider",n(s).themeColorsHueDynamic?"opacity-25 cursor-not-allowed":"cursor-pointer"]),disabled:n(s).themeColorsHueDynamic},null,10,be),[[Q,n(s).themeColorsHue]]),t[9]||(t[9]=e("div",{class:"color-bar"},[e("span",{"bg-primary-50":""},"50"),e("span",{"bg-primary-100":""},"100"),e("span",{"bg-primary-200":""},"200"),e("span",{"bg-primary-300":""},"300"),e("span",{"bg-primary-400":""},"400"),e("span",{"bg-primary-500":""},"500"),e("div",{"text-white":""},[e("span",{"bg-primary-600":""},"600"),e("span",{"bg-primary-700":""},"700"),e("span",{"bg-primary-800":""},"800"),e("span",{"bg-primary-900":""},"900"),e("span",{"bg-primary-950":""},"950")])],-1)),t[10]||(t[10]=e("div",{class:"color-bar transparency-grid"},[e("span",{bg:"primary-500/5"},"500/5"),e("span",{bg:"primary-500/10"},"500/10"),e("span",{bg:"primary-500/20"},"500/20"),e("span",{bg:"primary-500/30"},"500/30"),e("span",{bg:"primary-500/40"},"500/40"),e("span",{bg:"primary-500/50"},"500/50"),e("span",{bg:"primary-500/60"},"500/60"),e("span",{bg:"primary-500/70"},"500/70"),e("span",{bg:"primary-500/80"},"500/80"),e("span",{bg:"primary-500/90"},"500/90"),e("span",{bg:"primary-500"},"500")],-1))]),_:1}),l(f,{title:"settings.pages.themes.sections.section.theme-presets.title",icon:"i-solar:magic-stick-2-bold-duotone"},{default:g(()=>[(r(!0),d(B,null,W(i.$tm("settings.pages.themes.sections.section.theme-presets.presets"),({title:o,description:T,colors:F},x)=>(r(),d("div",{key:x,class:"setting-bar",bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},[e("div",null,[e("span",fe,a(i.$rt(o)),1),e("div",ye,a(i.$rt(T)),1)]),l(Y,{colors:F.map((U,H)=>({hex:n(se)[x][H],name:i.$rt(U)}))},null,8,["colors"])]))),128))]),_:1}),l(f,{title:"settings.pages.themes.sections.section.developer.title",icon:"i-solar:code-bold-duotone"},{default:g(()=>[l(y,{modelValue:n(s).disableTransitions,"onUpdate:modelValue":t[5]||(t[5]=o=>n(s).disableTransitions=o),"icon-on":"i-solar:people-nearby-bold-duotone","icon-off":"i-solar:running-2-line-duotone",text:"settings.animations.stage-transitions.title"},null,8,["modelValue"]),l(y,{modelValue:n(s).usePageSpecificTransitions,"onUpdate:modelValue":t[6]||(t[6]=o=>n(s).usePageSpecificTransitions=o),disabled:n(s).disableTransitions,"icon-on":"i-solar:running-2-line-duotone","icon-off":"i-solar:people-nearby-bold-duotone",text:"settings.animations.use-page-specific-transitions.title",description:"settings.animations.use-page-specific-transitions.description"},null,8,["modelValue","disabled"])]),_:1}),n(V)&&!b.value?(r(),J(E,{key:0,"z-index":-1,duration:1e3,started:n($),"is-reverse":!0,icon:n(w),"icon-size":12,position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)","text-color":"text-neutral-200/50 dark:text-neutral-600/20"},null,8,["started","icon"])):h("",!0),n(s).usePageSpecificTransitions?h("",!0):(r(),d("div",ve,t[11]||(t[11]=[e("div",{text:"40","i-lucide:paintbrush":""},null,-1)])))],64)}}});typeof k=="function"&&k(_);const $e=X(_,[["__scopeId","data-v-1285983e"]]);export{$e as default}; diff --git a/assets/index-Du8ix7FM.js b/assets/index-exdkhaXa.js similarity index 97% rename from assets/index-Du8ix7FM.js rename to assets/index-exdkhaXa.js index e27a3de43c089d0484d2085c4b5202e1a8a58118..ffb14e91de755a4fa3e2e90d911387d3a16796cd 100644 --- a/assets/index-Du8ix7FM.js +++ b/assets/index-exdkhaXa.js @@ -1 +1 @@ -import{_ as mt}from"./IconAnimation.vue_vue_type_script_setup_true_lang-KbGmnq0P.js";import{_ as dt,a as gt}from"./Model.vue_vue_type_script_setup_true_lang-DfGKadm0.js";import{k as nt,l as ft,m as _t,J as bt}from"./live2d-zip-loader-BdiFCiUD.js";import{d as Y,v as Z,c as O,o as z,e as p,p as vt,i as ut,bK as pt,s as wt,g as R,w as xt,bL as Ct,b as S,x as ct,C as q,y as E,a as y,A as W,bJ as Mt,bH as F,D as U,bx as J,by as rt,bI as kt,bn as Lt,bE as yt,l as Vt,bw as Dt}from"./index-rD0Uu1v9.js";import{_ as ot,a as St}from"./Section.vue_vue_type_script_setup_true_lang-BtOV76U1.js";import{u as zt}from"./useIconAnimation-BDdHp70p.js";import{b as st}from"./route-block-B_A1xBdJ.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";class It{constructor(t,e){this.pixels=t,this.opts=e;const{sigBits:i}=e,r=(M,L,v)=>(M<<2*i)+(L<>o,u=u>>o,d=d>>o;const L=r(l,u,d);a[L]===void 0&&(a[L]=0),a[L]+=1,l>c&&(c=l),lm&&(m=u),u_&&(_=d),dL>0?M+1:M,0),this.hist=a,this.rmax=c,this.rmin=h,this.gmax=m,this.gmin=f,this.bmax=_,this.bmin=b}get colorCount(){return this._colorCount}}class Nt{scaleDown(t){const e=this.getWidth(),i=this.getHeight();let r=1;if(t.maxDimension>0){const o=Math.max(e,i);o>t.maxDimension&&(r=t.maxDimension/o)}else r=1/t.quality;r<1&&this.resize(e*r,i*r,r)}}function Et(n,t){var e;if(t.length>0){const i=n.data,r=i.length/4;let o,s,a,c,h;for(let m=0;m{const s=()=>{this._initCanvas(),r(this)};e.complete?s():(e.onload=s,e.onerror=a=>o(new Error(`Fail to load image: ${i}`)))})}clear(){this._getContext().clearRect(0,0,this._getWidth(),this._getHeight())}update(t){this._getContext().putImageData(t,0,0)}getWidth(){return this._getWidth()}getHeight(){return this._getHeight()}resize(t,e,i){if(!this.image)throw new Error("Image is not initialized");this._width=this._getCanvas().width=t,this._height=this._getCanvas().height=e,this._getContext().scale(i,i),this._getContext().drawImage(this.image,0,0)}getPixelCount(){return this._getWidth()*this._getHeight()}getImageData(){return this._getContext().getImageData(0,0,this._getWidth(),this._getHeight())}remove(){this._canvas&&this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas)}}function T(n,...t){return t.forEach(e=>{if(e){for(const i in e)if(e.hasOwnProperty(i)){const r=e[i];Array.isArray(r)?n[i]=r.slice(0):typeof r=="object"?(n[i]||(n[i]={}),T(n[i],r)):n[i]=r}}}),n}function $t(n,t){const{colorCount:e,quantizer:i,generators:r,filters:o}=n,s={colorCount:e},a=typeof i=="string"?{name:i,options:{}}:i;return a.options=T({},s,a.options),T({},{quantizer:a,generators:r,filters:o},t)}class jt{constructor(t,e={}){this._src=t,this._opts=T({},P.DefaultOpts,e)}maxColorCount(t){return this._opts.colorCount=t,this}maxDimension(t){return this._opts.maxDimension=t,this}addFilter(t){return this._opts.filters?this._opts.filters.push(t):this._opts.filters=[t],this}removeFilter(t){if(this._opts.filters){const e=this._opts.filters.indexOf(t);e>0&&this._opts.filters.splice(e)}return this}clearFilters(){return this._opts.filters=[],this}quality(t){return this._opts.quality=t,this}useImageClass(t){return this._opts.ImageClass=t,this}useGenerator(t,e){return this._opts.generators||(this._opts.generators=[]),this._opts.generators.push(e?{name:t,options:e}:t),this}useQuantizer(t,e){return this._opts.quantizer=e?{name:t,options:e}:t,this}build(){return new P(this._src,this._opts)}getPalette(){return this.build().getPalette()}}class B{constructor(t){this.pipeline=t,this._map={}}names(){return Object.keys(this._map)}has(t){return!!this._map[t]}get(t){return this._map[t]}register(t,e){return this._map[t]=e,this.pipeline}}class Ut{constructor(){this.filter=new B(this),this.quantizer=new B(this),this.generator=new B(this)}_buildProcessTasks({filters:t,quantizer:e,generators:i}){return i.length===1&&i[0]==="*"&&(i=this.generator.names()),{filters:t.map(o=>r(this.filter,o)),quantizer:r(this.quantizer,e),generators:i.map(o=>r(this.generator,o))};function r(o,s){let a,c;return typeof s=="string"?a=s:(a=s.name,c=s.options),{name:a,fn:o.get(a),options:c}}}async process(t,e){const{filters:i,quantizer:r,generators:o}=this._buildProcessTasks(e),s=await this._filterColors(i,t),a=await this._generateColors(r,s),c=await this._generatePalettes(o,a);return{colors:a,palettes:c}}_filterColors(t,e){return Promise.resolve(Et(e,t.map(({fn:i})=>i)))}_generateColors(t,e){return Promise.resolve(t.fn(e.data,t.options))}async _generatePalettes(t,e){const i=await Promise.all(t.map(({fn:r,options:o})=>Promise.resolve(r(e,o))));return Promise.resolve(i.reduce((r,o,s)=>(r[t[s].name]=o,r),{}))}}function Tt(n,t,e){return"#"+((1<<24)+(n<<16)+(t<<8)+e).toString(16).slice(1,7)}function Rt(n,t,e){n/=255,t/=255,e/=255;const i=Math.max(n,t,e),r=Math.min(n,t,e);let o=0,s=0;const a=(i+r)/2;if(i!==r){const c=i-r;switch(s=a>.5?c/(2-i-r):c/(i+r),i){case n:o=(t-e)/c+(t1&&(h-=1),h<1/6?a+(c-a)*6*h:h<1/2?c:h<2/3?a+(c-a)*(2/3-h)*6:a}if(t===0)i=r=o=e;else{const a=e<.5?e*(1+t):e+t-e*t,c=2*e-a;i=s(c,a,n+1/3),r=s(c,a,n),o=s(c,a,n-1/3)}return[i*255,r*255,o*255]}class V{static applyFilters(t,e){return e.length>0?t.filter(({r:i,g:r,b:o})=>{var s;for(let a=0;a>=H,i>>=H,r>>=H,e>=o&&e<=s&&i>=a&&i<=c&&r>=h&&r<=m}split(){const{hist:t,getColorIndex:e}=this.histogram,{r1:i,r2:r,g1:o,g2:s,b1:a,b2:c}=this.dimension,h=this.count();if(!h)return[];if(h===1)return[this.clone()];const m=r-i+1,f=s-o+1,_=c-a+1,b=Math.max(m,f,_);let l=null,u,d;u=d=0;let g=null;if(b===m){g="r",l=new Uint32Array(r+1);for(let v=i;v<=r;v++){u=0;for(let x=o;x<=s;x++)for(let C=a;C<=c;C++){const D=e(v,x,C);t[D]&&(u+=t[D])}d+=u,l[v]=d}}else if(b===f){g="g",l=new Uint32Array(s+1);for(let v=o;v<=s;v++){u=0;for(let x=i;x<=r;x++)for(let C=a;C<=c;C++){const D=e(x,v,C);t[D]&&(u+=t[D])}d+=u,l[v]=d}}else{g="b",l=new Uint32Array(c+1);for(let v=a;v<=c;v++){u=0;for(let x=i;x<=r;x++)for(let C=o;C<=s;C++){const D=e(x,C,v);t[D]&&(u+=t[D])}d+=u,l[v]=d}}let w=-1;const I=new Uint32Array(l.length);for(let v=0;vd/2&&(w=v),I[v]=d-x)}const M=this;function L(v){const x=v+"1",C=v+"2",D=M.dimension[x];let k=M.dimension[C];const K=M.clone(),X=M.clone(),tt=w-D,et=k-w;for(tt<=et?(k=Math.min(k-1,~~(w+et/2)),k=Math.max(0,k)):(k=Math.max(D,~~(w-1-tt/2)),k=Math.min(M.dimension[C],k));!l[k];)k++;let it=I[k];for(;!it&&l[k-1];)it=I[--k];return K.dimension[C]=k,X.dimension[x]=k+1,[K,X]}return L(g)}}class at{_sort(){this._sorted||(this.contents.sort(this._comparator),this._sorted=!0)}constructor(t){this._comparator=t,this.contents=[],this._sorted=!1}push(t){this.contents.push(t),this._sorted=!1}peek(t){return this._sort(),t=typeof t=="number"?t:this.contents.length-1,this.contents[t]}pop(){return this._sort(),this.contents.pop()}size(){return this.contents.length}map(t){return this._sort(),this.contents.map(t)}}const At=.75;function lt(n,t){let e=n.size();for(;n.size()0){const[r,o]=i.split();if(!r||(n.push(r),o&&o.count()>0&&n.push(o),n.size()===e))break;e=n.size()}else break}}const Bt=(n,t)=>{if(n.length===0||t.colorCount<2||t.colorCount>256)throw new Error("Wrong MMCQ parameters");const e=A.build(n);e.histogram.colorCount;const i=new at((o,s)=>o.count()-s.count());i.push(e),lt(i,At*t.colorCount);const r=new at((o,s)=>o.count()*o.volume()-s.count()*s.volume());return r.contents=i.contents,lt(r,t.colorCount-r.size()),Ht(r)};function Ht(n){const t=[];for(;n.size();){const e=n.pop(),i=e.avg();t.push(new V(i,e.count()))}return t}const qt={targetDarkLuma:.26,maxDarkLuma:.45,minLightLuma:.55,targetLightLuma:.74,minNormalLuma:.3,targetNormalLuma:.5,maxNormalLuma:.7,targetMutesSaturation:.3,maxMutesSaturation:.4,targetVibrantSaturation:1,minVibrantSaturation:.35,weightSaturation:3,weightLuma:6.5,weightPopulation:.5};function Wt(n){let t=0;return n.forEach(e=>{t=Math.max(t,e.population)}),t}function Jt(n,t){return n.Vibrant===t||n.DarkVibrant===t||n.LightVibrant===t||n.Muted===t||n.DarkMuted===t||n.LightMuted===t}function Qt(n,t,e,i,r,o,s){function a(...h){let m=0,f=0;for(let _=0;_{const[,b,l]=_.hsl;if(b>=a&&b<=c&&l>=r&&l<=o&&!Jt(n,_)){const u=Qt(b,s,l,i,_.population,e,h);(m===null||u>f)&&(m=_,f=u)}}),m}function Gt(n,t,e){const i={Vibrant:null,DarkVibrant:null,LightVibrant:null,Muted:null,DarkMuted:null,LightMuted:null};return i.Vibrant=$(i,n,t,e.targetNormalLuma,e.minNormalLuma,e.maxNormalLuma,e.targetVibrantSaturation,e.minVibrantSaturation,1,e),i.LightVibrant=$(i,n,t,e.targetLightLuma,e.minLightLuma,1,e.targetVibrantSaturation,e.minVibrantSaturation,1,e),i.DarkVibrant=$(i,n,t,e.targetDarkLuma,0,e.maxDarkLuma,e.targetVibrantSaturation,e.minVibrantSaturation,1,e),i.Muted=$(i,n,t,e.targetNormalLuma,e.minNormalLuma,e.maxNormalLuma,e.targetMutesSaturation,0,e.maxMutesSaturation,e),i.LightMuted=$(i,n,t,e.targetLightLuma,e.minLightLuma,1,e.targetMutesSaturation,0,e.maxMutesSaturation,e),i.DarkMuted=$(i,n,t,e.targetDarkLuma,0,e.maxDarkLuma,e.targetMutesSaturation,0,e.maxMutesSaturation,e),i}function Yt(n,t,e){if(!n.Vibrant&&!n.DarkVibrant&&!n.LightVibrant){if(!n.DarkVibrant&&n.DarkMuted){let[i,r,o]=n.DarkMuted.hsl;o=e.targetDarkLuma,n.DarkVibrant=new V(N(i,r,o),0)}if(!n.LightVibrant&&n.LightMuted){let[i,r,o]=n.LightMuted.hsl;o=e.targetDarkLuma,n.DarkVibrant=new V(N(i,r,o),0)}}if(!n.Vibrant&&n.DarkVibrant){let[i,r,o]=n.DarkVibrant.hsl;o=e.targetNormalLuma,n.Vibrant=new V(N(i,r,o),0)}else if(!n.Vibrant&&n.LightVibrant){let[i,r,o]=n.LightVibrant.hsl;o=e.targetNormalLuma,n.Vibrant=new V(N(i,r,o),0)}if(!n.DarkVibrant&&n.Vibrant){let[i,r,o]=n.Vibrant.hsl;o=e.targetDarkLuma,n.DarkVibrant=new V(N(i,r,o),0)}if(!n.LightVibrant&&n.Vibrant){let[i,r,o]=n.Vibrant.hsl;o=e.targetLightLuma,n.LightVibrant=new V(N(i,r,o),0)}if(!n.Muted&&n.Vibrant){let[i,r,o]=n.Vibrant.hsl;o=e.targetMutesSaturation,n.Muted=new V(N(i,r,o),0)}if(!n.DarkMuted&&n.DarkVibrant){let[i,r,o]=n.DarkVibrant.hsl;o=e.targetMutesSaturation,n.DarkMuted=new V(N(i,r,o),0)}if(!n.LightMuted&&n.LightVibrant){let[i,r,o]=n.LightVibrant.hsl;o=e.targetMutesSaturation,n.LightMuted=new V(N(i,r,o),0)}}const Zt=(n,t)=>{t=Object.assign({},qt,t);const e=Wt(n),i=Gt(n,e,t);return Yt(i,e,t),i},Kt=new Ut().filter.register("default",(n,t,e,i)=>i>=125&&!(n>250&&t>250&&e>250)).quantizer.register("mmcq",Bt).generator.register("default",Zt);P.use(Kt);const Xt=["disabled"],j=Y({__name:"Live2DModelControlButton",emits:["click"],setup(n){const t=Z();return(e,i)=>(z(),O("button",{disabled:p(t).loadingLive2dModel,bg:"zinc-100 dark:zinc-800",hover:"bg-zinc-200 dark:bg-zinc-700",transition:"all ease-in-out duration-250",rounded:"",onClick:i[0]||(i[0]=r=>e.$emit("click"))},[vt(e.$slots,"default")],8,Xt))}}),te={flex:"~ col gap-4"},ee={flex:"","items-center":"","gap-2":""},ie=["disabled","placeholder"],ne={"font-medium":""},re={flex:"","gap-2":""},oe=["onUpdate:modelValue"],se=["href","download"],ae=Y({__name:"Live2DSettings",props:{palette:null},emits:["extractColorsFromModel"],setup(n){const{t}=ut(),e=pt({accept:"application/zip"}),i=Z(),{live2dModelFile:r,live2dMotionMap:o,live2dLoadSource:s,loadingLive2dModel:a,availableLive2dMotions:c,live2dModelUrl:h}=wt(i),m=R(h.value);e.onChange(l=>{l&&l.length>0&&(o.value={},r.value=l[0],s.value="file",a.value=!0)}),xt(()=>i.loadingLive2dModel,l=>{l||s.value==="file"&&c.value.forEach(u=>{u.motionName in nt?o.value[u.fileName]=u.motionName:o.value[u.fileName]=ft})});async function f(l,u){if(!Object.keys(u).length)return l;const g=await new bt().loadAsync(l),w=Object.keys(g.files).find(x=>x.endsWith("model3.json"));if(!w)throw new Error("model3.json not found");const I=await g.file(w).async("string"),M=JSON.parse(I),L={};Object.entries(u).forEach(([x,C])=>{if(L[C]){L[C].push({File:x});return}L[C]=[{File:x}]}),M.FileReferences.Motions=L,g.file(w,JSON.stringify(M,null,2));const v=await g.generateAsync({type:"blob"});return new File([v],l.name,{type:l.type,lastModified:l.lastModified})}async function _(){const l=await _t.getItem("live2dModel");if(!l)return;const u=await f(l,o.value);r.value=u,s.value="file",a.value=!0}const b=Ct(r);return(l,u)=>(z(),O("div",te,[S(ot,{title:"settings.live2d.change-model.title",icon:"i-solar:magic-stick-3-bold-duotone","inner-class":"text-sm"},{default:E(()=>[y("div",ee,[W(y("input",{"onUpdate:modelValue":u[0]||(u[0]=d=>m.value=d),disabled:p(i).loadingLive2dModel,class:"form-control flex-1",border:"zinc-300 dark:zinc-800 solid 1 focus:zinc-400 dark:focus:zinc-600",transition:"border duration-250 ease-in-out",placeholder:p(t)("settings.live2d.change-model.from-url-placeholder")},null,8,ie),[[Mt,m.value]]),S(j,{class:"form-control",onClick:u[1]||(u[1]=d=>h.value=m.value)},{default:E(()=>[F(U(p(t)("settings.live2d.change-model.from-url")),1)]),_:1})]),S(j,{class:"form-control place-self-end",onClick:u[2]||(u[2]=d=>p(e).open())},{default:E(()=>[F(U(p(t)("settings.live2d.change-model.from-file"))+"... ",1)]),_:1}),S(j,{class:"form-control",onClick:u[3]||(u[3]=d=>l.$emit("extractColorsFromModel"))},{default:E(()=>u[4]||(u[4]=[F(" Extract colors from model ")])),_:1}),S(St,{colors:n.palette.map(d=>({hex:d,name:d}))},null,8,["colors"])]),_:1}),p(i).live2dLoadSource==="file"?(z(),ct(ot,{key:0,title:"settings.live2d.edit-motion-map.title",icon:"i-solar:face-scan-circle-bold-duotone"},{default:E(()=>{var d;return[(z(!0),O(J,null,rt(p(i).availableLive2dMotions,g=>(z(),O("div",{key:g.fileName,flex:"","items-center":"","justify-between":"","text-sm":""},[y("span",ne,U(g.fileName),1),y("div",re,[W(y("select",{"onUpdate:modelValue":w=>p(i).live2dMotionMap[g.fileName]=w},[(z(!0),O(J,null,rt(Object.keys(p(nt)),w=>(z(),O("option",{key:w},U(w),1))),128))],8,oe),[[kt,p(i).live2dMotionMap[g.fileName]]]),S(j,{class:"form-control",onClick:w=>p(i).live2dCurrentMotion={group:g.motionName,index:g.motionIndex}},{default:E(()=>u[5]||(u[5]=[F(" Play ")])),_:2},1032,["onClick"])])]))),128)),S(j,{onClick:_},{default:E(()=>u[6]||(u[6]=[F(" Save and patch ")])),_:1}),y("a",{"mt-2":"",block:"",href:p(b),download:`${((d=p(i).live2dModelFile)==null?void 0:d.name)||"live2d"}-motion-edited.zip`},[S(j,{"w-full":""},{default:E(()=>u[7]||(u[7]=[F("Export")])),_:1})],8,se)]}),_:1})):q("",!0)]))}}),le=Lt(ae,[["__scopeId","data-v-c23b784f"]]),ue={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},ce={relative:"","text-nowrap":""},he={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]",text:"neutral-300 dark:neutral-500"},me={"text-3xl":"","font-semibold":""},de={flex:""},ge={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},fe=Y({__name:"index",setup(n){const{t}=ut(),e=yt(),i=R(),r=R(),{width:o,height:s}=Vt(i),a=Z(),c=R([]);async function h(){if(!r.value)return;const b=await r.value.captureFrame();if(!b){console.error("No frame captured");return}const l=URL.createObjectURL(b);try{const d=await new P(l).getPalette();c.value=Object.values(d).map(g=>g==null?void 0:g.hex).filter(g=>typeof g=="string")}finally{URL.revokeObjectURL(l)}}const{iconAnimationStarted:m,showIconAnimation:f,animationIcon:_}=zt("i-lucide:person-standing");return(b,l)=>{const u=mt,d=Dt("motion");return z(),O(J,null,[W((z(),O("div",ue,[y("button",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":"",onClick:l[0]||(l[0]=g=>p(e).back())}),y("h1",ce,[y("div",he,U(p(t)("settings.title")),1),y("div",me,U(p(t)("settings.pages.models.title")),1)])])),[[d]]),y("div",de,[y("div",{ref_key:"live2dContainerRef",ref:i,w:"50%",h:"80vh"},[S(gt,{ref_key:"live2dCanvasRef",ref:r,width:p(o),height:p(s)},{default:E(({app:g})=>[S(dt,{app:g,"mouth-open-size":0,width:p(o),height:p(s),paused:!1},null,8,["app","width","height"])]),_:1},8,["width","height"])],512),S(le,{w:"50%",h:"80vh",palette:c.value,onExtractColorsFromModel:h},null,8,["palette"])]),p(f)?(z(),ct(u,{key:0,"z-index":-1,icon:p(_),"icon-size":12,duration:1e3,started:p(m),"is-reverse":!0,position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)","text-color":"text-neutral-200/50 dark:text-neutral-600/20"},null,8,["icon","started"])):q("",!0),p(a).usePageSpecificTransitions?q("",!0):(z(),O("div",ge,l[1]||(l[1]=[y("div",{text:"40","i-lucide:person-standing":""},null,-1)])))],64)}}});typeof st=="function"&&st(fe);export{fe as default}; +import{_ as mt}from"./IconAnimation.vue_vue_type_script_setup_true_lang-D7WFDasI.js";import{_ as dt,a as gt}from"./Model.vue_vue_type_script_setup_true_lang-CSqfK4Nz.js";import{k as nt,l as ft,m as _t,J as bt}from"./live2d-zip-loader-C5j9stxV.js";import{d as Y,v as Z,c as O,o as z,e as p,p as vt,i as ut,bK as pt,s as wt,g as R,w as xt,bL as Ct,b as S,x as ct,C as q,y as E,a as y,A as W,bJ as Mt,bH as F,D as U,bx as J,by as rt,bI as kt,bn as Lt,bE as yt,l as Vt,bw as Dt}from"./index-Dlp4W1Zl.js";import{_ as ot,a as St}from"./Section.vue_vue_type_script_setup_true_lang-Ju8FFDso.js";import{u as zt}from"./useIconAnimation-DMJpspm5.js";import{b as st}from"./route-block-B_A1xBdJ.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";class It{constructor(t,e){this.pixels=t,this.opts=e;const{sigBits:i}=e,r=(M,L,v)=>(M<<2*i)+(L<>o,u=u>>o,d=d>>o;const L=r(l,u,d);a[L]===void 0&&(a[L]=0),a[L]+=1,l>c&&(c=l),lm&&(m=u),u_&&(_=d),dL>0?M+1:M,0),this.hist=a,this.rmax=c,this.rmin=h,this.gmax=m,this.gmin=f,this.bmax=_,this.bmin=b}get colorCount(){return this._colorCount}}class Nt{scaleDown(t){const e=this.getWidth(),i=this.getHeight();let r=1;if(t.maxDimension>0){const o=Math.max(e,i);o>t.maxDimension&&(r=t.maxDimension/o)}else r=1/t.quality;r<1&&this.resize(e*r,i*r,r)}}function Et(n,t){var e;if(t.length>0){const i=n.data,r=i.length/4;let o,s,a,c,h;for(let m=0;m{const s=()=>{this._initCanvas(),r(this)};e.complete?s():(e.onload=s,e.onerror=a=>o(new Error(`Fail to load image: ${i}`)))})}clear(){this._getContext().clearRect(0,0,this._getWidth(),this._getHeight())}update(t){this._getContext().putImageData(t,0,0)}getWidth(){return this._getWidth()}getHeight(){return this._getHeight()}resize(t,e,i){if(!this.image)throw new Error("Image is not initialized");this._width=this._getCanvas().width=t,this._height=this._getCanvas().height=e,this._getContext().scale(i,i),this._getContext().drawImage(this.image,0,0)}getPixelCount(){return this._getWidth()*this._getHeight()}getImageData(){return this._getContext().getImageData(0,0,this._getWidth(),this._getHeight())}remove(){this._canvas&&this._canvas.parentNode&&this._canvas.parentNode.removeChild(this._canvas)}}function T(n,...t){return t.forEach(e=>{if(e){for(const i in e)if(e.hasOwnProperty(i)){const r=e[i];Array.isArray(r)?n[i]=r.slice(0):typeof r=="object"?(n[i]||(n[i]={}),T(n[i],r)):n[i]=r}}}),n}function $t(n,t){const{colorCount:e,quantizer:i,generators:r,filters:o}=n,s={colorCount:e},a=typeof i=="string"?{name:i,options:{}}:i;return a.options=T({},s,a.options),T({},{quantizer:a,generators:r,filters:o},t)}class jt{constructor(t,e={}){this._src=t,this._opts=T({},P.DefaultOpts,e)}maxColorCount(t){return this._opts.colorCount=t,this}maxDimension(t){return this._opts.maxDimension=t,this}addFilter(t){return this._opts.filters?this._opts.filters.push(t):this._opts.filters=[t],this}removeFilter(t){if(this._opts.filters){const e=this._opts.filters.indexOf(t);e>0&&this._opts.filters.splice(e)}return this}clearFilters(){return this._opts.filters=[],this}quality(t){return this._opts.quality=t,this}useImageClass(t){return this._opts.ImageClass=t,this}useGenerator(t,e){return this._opts.generators||(this._opts.generators=[]),this._opts.generators.push(e?{name:t,options:e}:t),this}useQuantizer(t,e){return this._opts.quantizer=e?{name:t,options:e}:t,this}build(){return new P(this._src,this._opts)}getPalette(){return this.build().getPalette()}}class B{constructor(t){this.pipeline=t,this._map={}}names(){return Object.keys(this._map)}has(t){return!!this._map[t]}get(t){return this._map[t]}register(t,e){return this._map[t]=e,this.pipeline}}class Ut{constructor(){this.filter=new B(this),this.quantizer=new B(this),this.generator=new B(this)}_buildProcessTasks({filters:t,quantizer:e,generators:i}){return i.length===1&&i[0]==="*"&&(i=this.generator.names()),{filters:t.map(o=>r(this.filter,o)),quantizer:r(this.quantizer,e),generators:i.map(o=>r(this.generator,o))};function r(o,s){let a,c;return typeof s=="string"?a=s:(a=s.name,c=s.options),{name:a,fn:o.get(a),options:c}}}async process(t,e){const{filters:i,quantizer:r,generators:o}=this._buildProcessTasks(e),s=await this._filterColors(i,t),a=await this._generateColors(r,s),c=await this._generatePalettes(o,a);return{colors:a,palettes:c}}_filterColors(t,e){return Promise.resolve(Et(e,t.map(({fn:i})=>i)))}_generateColors(t,e){return Promise.resolve(t.fn(e.data,t.options))}async _generatePalettes(t,e){const i=await Promise.all(t.map(({fn:r,options:o})=>Promise.resolve(r(e,o))));return Promise.resolve(i.reduce((r,o,s)=>(r[t[s].name]=o,r),{}))}}function Tt(n,t,e){return"#"+((1<<24)+(n<<16)+(t<<8)+e).toString(16).slice(1,7)}function Rt(n,t,e){n/=255,t/=255,e/=255;const i=Math.max(n,t,e),r=Math.min(n,t,e);let o=0,s=0;const a=(i+r)/2;if(i!==r){const c=i-r;switch(s=a>.5?c/(2-i-r):c/(i+r),i){case n:o=(t-e)/c+(t1&&(h-=1),h<1/6?a+(c-a)*6*h:h<1/2?c:h<2/3?a+(c-a)*(2/3-h)*6:a}if(t===0)i=r=o=e;else{const a=e<.5?e*(1+t):e+t-e*t,c=2*e-a;i=s(c,a,n+1/3),r=s(c,a,n),o=s(c,a,n-1/3)}return[i*255,r*255,o*255]}class V{static applyFilters(t,e){return e.length>0?t.filter(({r:i,g:r,b:o})=>{var s;for(let a=0;a>=H,i>>=H,r>>=H,e>=o&&e<=s&&i>=a&&i<=c&&r>=h&&r<=m}split(){const{hist:t,getColorIndex:e}=this.histogram,{r1:i,r2:r,g1:o,g2:s,b1:a,b2:c}=this.dimension,h=this.count();if(!h)return[];if(h===1)return[this.clone()];const m=r-i+1,f=s-o+1,_=c-a+1,b=Math.max(m,f,_);let l=null,u,d;u=d=0;let g=null;if(b===m){g="r",l=new Uint32Array(r+1);for(let v=i;v<=r;v++){u=0;for(let x=o;x<=s;x++)for(let C=a;C<=c;C++){const D=e(v,x,C);t[D]&&(u+=t[D])}d+=u,l[v]=d}}else if(b===f){g="g",l=new Uint32Array(s+1);for(let v=o;v<=s;v++){u=0;for(let x=i;x<=r;x++)for(let C=a;C<=c;C++){const D=e(x,v,C);t[D]&&(u+=t[D])}d+=u,l[v]=d}}else{g="b",l=new Uint32Array(c+1);for(let v=a;v<=c;v++){u=0;for(let x=i;x<=r;x++)for(let C=o;C<=s;C++){const D=e(x,C,v);t[D]&&(u+=t[D])}d+=u,l[v]=d}}let w=-1;const I=new Uint32Array(l.length);for(let v=0;vd/2&&(w=v),I[v]=d-x)}const M=this;function L(v){const x=v+"1",C=v+"2",D=M.dimension[x];let k=M.dimension[C];const K=M.clone(),X=M.clone(),tt=w-D,et=k-w;for(tt<=et?(k=Math.min(k-1,~~(w+et/2)),k=Math.max(0,k)):(k=Math.max(D,~~(w-1-tt/2)),k=Math.min(M.dimension[C],k));!l[k];)k++;let it=I[k];for(;!it&&l[k-1];)it=I[--k];return K.dimension[C]=k,X.dimension[x]=k+1,[K,X]}return L(g)}}class at{_sort(){this._sorted||(this.contents.sort(this._comparator),this._sorted=!0)}constructor(t){this._comparator=t,this.contents=[],this._sorted=!1}push(t){this.contents.push(t),this._sorted=!1}peek(t){return this._sort(),t=typeof t=="number"?t:this.contents.length-1,this.contents[t]}pop(){return this._sort(),this.contents.pop()}size(){return this.contents.length}map(t){return this._sort(),this.contents.map(t)}}const At=.75;function lt(n,t){let e=n.size();for(;n.size()0){const[r,o]=i.split();if(!r||(n.push(r),o&&o.count()>0&&n.push(o),n.size()===e))break;e=n.size()}else break}}const Bt=(n,t)=>{if(n.length===0||t.colorCount<2||t.colorCount>256)throw new Error("Wrong MMCQ parameters");const e=A.build(n);e.histogram.colorCount;const i=new at((o,s)=>o.count()-s.count());i.push(e),lt(i,At*t.colorCount);const r=new at((o,s)=>o.count()*o.volume()-s.count()*s.volume());return r.contents=i.contents,lt(r,t.colorCount-r.size()),Ht(r)};function Ht(n){const t=[];for(;n.size();){const e=n.pop(),i=e.avg();t.push(new V(i,e.count()))}return t}const qt={targetDarkLuma:.26,maxDarkLuma:.45,minLightLuma:.55,targetLightLuma:.74,minNormalLuma:.3,targetNormalLuma:.5,maxNormalLuma:.7,targetMutesSaturation:.3,maxMutesSaturation:.4,targetVibrantSaturation:1,minVibrantSaturation:.35,weightSaturation:3,weightLuma:6.5,weightPopulation:.5};function Wt(n){let t=0;return n.forEach(e=>{t=Math.max(t,e.population)}),t}function Jt(n,t){return n.Vibrant===t||n.DarkVibrant===t||n.LightVibrant===t||n.Muted===t||n.DarkMuted===t||n.LightMuted===t}function Qt(n,t,e,i,r,o,s){function a(...h){let m=0,f=0;for(let _=0;_{const[,b,l]=_.hsl;if(b>=a&&b<=c&&l>=r&&l<=o&&!Jt(n,_)){const u=Qt(b,s,l,i,_.population,e,h);(m===null||u>f)&&(m=_,f=u)}}),m}function Gt(n,t,e){const i={Vibrant:null,DarkVibrant:null,LightVibrant:null,Muted:null,DarkMuted:null,LightMuted:null};return i.Vibrant=$(i,n,t,e.targetNormalLuma,e.minNormalLuma,e.maxNormalLuma,e.targetVibrantSaturation,e.minVibrantSaturation,1,e),i.LightVibrant=$(i,n,t,e.targetLightLuma,e.minLightLuma,1,e.targetVibrantSaturation,e.minVibrantSaturation,1,e),i.DarkVibrant=$(i,n,t,e.targetDarkLuma,0,e.maxDarkLuma,e.targetVibrantSaturation,e.minVibrantSaturation,1,e),i.Muted=$(i,n,t,e.targetNormalLuma,e.minNormalLuma,e.maxNormalLuma,e.targetMutesSaturation,0,e.maxMutesSaturation,e),i.LightMuted=$(i,n,t,e.targetLightLuma,e.minLightLuma,1,e.targetMutesSaturation,0,e.maxMutesSaturation,e),i.DarkMuted=$(i,n,t,e.targetDarkLuma,0,e.maxDarkLuma,e.targetMutesSaturation,0,e.maxMutesSaturation,e),i}function Yt(n,t,e){if(!n.Vibrant&&!n.DarkVibrant&&!n.LightVibrant){if(!n.DarkVibrant&&n.DarkMuted){let[i,r,o]=n.DarkMuted.hsl;o=e.targetDarkLuma,n.DarkVibrant=new V(N(i,r,o),0)}if(!n.LightVibrant&&n.LightMuted){let[i,r,o]=n.LightMuted.hsl;o=e.targetDarkLuma,n.DarkVibrant=new V(N(i,r,o),0)}}if(!n.Vibrant&&n.DarkVibrant){let[i,r,o]=n.DarkVibrant.hsl;o=e.targetNormalLuma,n.Vibrant=new V(N(i,r,o),0)}else if(!n.Vibrant&&n.LightVibrant){let[i,r,o]=n.LightVibrant.hsl;o=e.targetNormalLuma,n.Vibrant=new V(N(i,r,o),0)}if(!n.DarkVibrant&&n.Vibrant){let[i,r,o]=n.Vibrant.hsl;o=e.targetDarkLuma,n.DarkVibrant=new V(N(i,r,o),0)}if(!n.LightVibrant&&n.Vibrant){let[i,r,o]=n.Vibrant.hsl;o=e.targetLightLuma,n.LightVibrant=new V(N(i,r,o),0)}if(!n.Muted&&n.Vibrant){let[i,r,o]=n.Vibrant.hsl;o=e.targetMutesSaturation,n.Muted=new V(N(i,r,o),0)}if(!n.DarkMuted&&n.DarkVibrant){let[i,r,o]=n.DarkVibrant.hsl;o=e.targetMutesSaturation,n.DarkMuted=new V(N(i,r,o),0)}if(!n.LightMuted&&n.LightVibrant){let[i,r,o]=n.LightVibrant.hsl;o=e.targetMutesSaturation,n.LightMuted=new V(N(i,r,o),0)}}const Zt=(n,t)=>{t=Object.assign({},qt,t);const e=Wt(n),i=Gt(n,e,t);return Yt(i,e,t),i},Kt=new Ut().filter.register("default",(n,t,e,i)=>i>=125&&!(n>250&&t>250&&e>250)).quantizer.register("mmcq",Bt).generator.register("default",Zt);P.use(Kt);const Xt=["disabled"],j=Y({__name:"Live2DModelControlButton",emits:["click"],setup(n){const t=Z();return(e,i)=>(z(),O("button",{disabled:p(t).loadingLive2dModel,bg:"zinc-100 dark:zinc-800",hover:"bg-zinc-200 dark:bg-zinc-700",transition:"all ease-in-out duration-250",rounded:"",onClick:i[0]||(i[0]=r=>e.$emit("click"))},[vt(e.$slots,"default")],8,Xt))}}),te={flex:"~ col gap-4"},ee={flex:"","items-center":"","gap-2":""},ie=["disabled","placeholder"],ne={"font-medium":""},re={flex:"","gap-2":""},oe=["onUpdate:modelValue"],se=["href","download"],ae=Y({__name:"Live2DSettings",props:{palette:null},emits:["extractColorsFromModel"],setup(n){const{t}=ut(),e=pt({accept:"application/zip"}),i=Z(),{live2dModelFile:r,live2dMotionMap:o,live2dLoadSource:s,loadingLive2dModel:a,availableLive2dMotions:c,live2dModelUrl:h}=wt(i),m=R(h.value);e.onChange(l=>{l&&l.length>0&&(o.value={},r.value=l[0],s.value="file",a.value=!0)}),xt(()=>i.loadingLive2dModel,l=>{l||s.value==="file"&&c.value.forEach(u=>{u.motionName in nt?o.value[u.fileName]=u.motionName:o.value[u.fileName]=ft})});async function f(l,u){if(!Object.keys(u).length)return l;const g=await new bt().loadAsync(l),w=Object.keys(g.files).find(x=>x.endsWith("model3.json"));if(!w)throw new Error("model3.json not found");const I=await g.file(w).async("string"),M=JSON.parse(I),L={};Object.entries(u).forEach(([x,C])=>{if(L[C]){L[C].push({File:x});return}L[C]=[{File:x}]}),M.FileReferences.Motions=L,g.file(w,JSON.stringify(M,null,2));const v=await g.generateAsync({type:"blob"});return new File([v],l.name,{type:l.type,lastModified:l.lastModified})}async function _(){const l=await _t.getItem("live2dModel");if(!l)return;const u=await f(l,o.value);r.value=u,s.value="file",a.value=!0}const b=Ct(r);return(l,u)=>(z(),O("div",te,[S(ot,{title:"settings.live2d.change-model.title",icon:"i-solar:magic-stick-3-bold-duotone","inner-class":"text-sm"},{default:E(()=>[y("div",ee,[W(y("input",{"onUpdate:modelValue":u[0]||(u[0]=d=>m.value=d),disabled:p(i).loadingLive2dModel,class:"form-control flex-1",border:"zinc-300 dark:zinc-800 solid 1 focus:zinc-400 dark:focus:zinc-600",transition:"border duration-250 ease-in-out",placeholder:p(t)("settings.live2d.change-model.from-url-placeholder")},null,8,ie),[[Mt,m.value]]),S(j,{class:"form-control",onClick:u[1]||(u[1]=d=>h.value=m.value)},{default:E(()=>[F(U(p(t)("settings.live2d.change-model.from-url")),1)]),_:1})]),S(j,{class:"form-control place-self-end",onClick:u[2]||(u[2]=d=>p(e).open())},{default:E(()=>[F(U(p(t)("settings.live2d.change-model.from-file"))+"... ",1)]),_:1}),S(j,{class:"form-control",onClick:u[3]||(u[3]=d=>l.$emit("extractColorsFromModel"))},{default:E(()=>u[4]||(u[4]=[F(" Extract colors from model ")])),_:1}),S(St,{colors:n.palette.map(d=>({hex:d,name:d}))},null,8,["colors"])]),_:1}),p(i).live2dLoadSource==="file"?(z(),ct(ot,{key:0,title:"settings.live2d.edit-motion-map.title",icon:"i-solar:face-scan-circle-bold-duotone"},{default:E(()=>{var d;return[(z(!0),O(J,null,rt(p(i).availableLive2dMotions,g=>(z(),O("div",{key:g.fileName,flex:"","items-center":"","justify-between":"","text-sm":""},[y("span",ne,U(g.fileName),1),y("div",re,[W(y("select",{"onUpdate:modelValue":w=>p(i).live2dMotionMap[g.fileName]=w},[(z(!0),O(J,null,rt(Object.keys(p(nt)),w=>(z(),O("option",{key:w},U(w),1))),128))],8,oe),[[kt,p(i).live2dMotionMap[g.fileName]]]),S(j,{class:"form-control",onClick:w=>p(i).live2dCurrentMotion={group:g.motionName,index:g.motionIndex}},{default:E(()=>u[5]||(u[5]=[F(" Play ")])),_:2},1032,["onClick"])])]))),128)),S(j,{onClick:_},{default:E(()=>u[6]||(u[6]=[F(" Save and patch ")])),_:1}),y("a",{"mt-2":"",block:"",href:p(b),download:`${((d=p(i).live2dModelFile)==null?void 0:d.name)||"live2d"}-motion-edited.zip`},[S(j,{"w-full":""},{default:E(()=>u[7]||(u[7]=[F("Export")])),_:1})],8,se)]}),_:1})):q("",!0)]))}}),le=Lt(ae,[["__scopeId","data-v-c23b784f"]]),ue={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},ce={relative:"","text-nowrap":""},he={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]",text:"neutral-300 dark:neutral-500"},me={"text-3xl":"","font-semibold":""},de={flex:""},ge={key:1,text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},fe=Y({__name:"index",setup(n){const{t}=ut(),e=yt(),i=R(),r=R(),{width:o,height:s}=Vt(i),a=Z(),c=R([]);async function h(){if(!r.value)return;const b=await r.value.captureFrame();if(!b){console.error("No frame captured");return}const l=URL.createObjectURL(b);try{const d=await new P(l).getPalette();c.value=Object.values(d).map(g=>g==null?void 0:g.hex).filter(g=>typeof g=="string")}finally{URL.revokeObjectURL(l)}}const{iconAnimationStarted:m,showIconAnimation:f,animationIcon:_}=zt("i-lucide:person-standing");return(b,l)=>{const u=mt,d=Dt("motion");return z(),O(J,null,[W((z(),O("div",ue,[y("button",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":"",onClick:l[0]||(l[0]=g=>p(e).back())}),y("h1",ce,[y("div",he,U(p(t)("settings.title")),1),y("div",me,U(p(t)("settings.pages.models.title")),1)])])),[[d]]),y("div",de,[y("div",{ref_key:"live2dContainerRef",ref:i,w:"50%",h:"80vh"},[S(gt,{ref_key:"live2dCanvasRef",ref:r,width:p(o),height:p(s)},{default:E(({app:g})=>[S(dt,{app:g,"mouth-open-size":0,width:p(o),height:p(s),paused:!1},null,8,["app","width","height"])]),_:1},8,["width","height"])],512),S(le,{w:"50%",h:"80vh",palette:c.value,onExtractColorsFromModel:h},null,8,["palette"])]),p(f)?(z(),ct(u,{key:0,"z-index":-1,icon:p(_),"icon-size":12,duration:1e3,started:p(m),"is-reverse":!0,position:"calc(100dvw - 9.5rem), calc(100dvh - 9.5rem)","text-color":"text-neutral-200/50 dark:text-neutral-600/20"},null,8,["icon","started"])):q("",!0),p(a).usePageSpecificTransitions?q("",!0):(z(),O("div",ge,l[1]||(l[1]=[y("div",{text:"40","i-lucide:person-standing":""},null,-1)])))],64)}}});typeof st=="function"&&st(fe);export{fe as default}; diff --git a/assets/live2d-zip-loader-BdiFCiUD.js b/assets/live2d-zip-loader-C5j9stxV.js similarity index 96% rename from assets/live2d-zip-loader-BdiFCiUD.js rename to assets/live2d-zip-loader-C5j9stxV.js index 29a5a55748eeafb8f4501f209e0f2568948b2519..73ee5dc6149a66c6593b0646110079021c66794b 100644 --- a/assets/live2d-zip-loader-BdiFCiUD.js +++ b/assets/live2d-zip-loader-C5j9stxV.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-node-CM_FKz7Y.js","assets/index-rD0Uu1v9.js","assets/index-DIu27PLL.css","assets/import-url-browser-CPN8ipMD.js","assets/duckdb-mvp-CaaD-olE.js","assets/import-url-node-BfNoxhRr.js"])))=>i.map(i=>d[i]); -var f1=Object.defineProperty;var p1=(r,t,e)=>t in r?f1(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var W=(r,t,e)=>p1(r,typeof t!="symbol"?t+"":t,e);import{bm as If,ci as Dn,b2 as m1,a0 as g1,a9 as Fe,V as mt,Q as ne,a3 as Ps,ba as No,av as Hp,ag as Xp,ak as Yp,b3 as ec,b6 as Ef,cj as y1,$ as v1,ck as _1,a1 as b1,cl as Ho,cm as xn,W as qr,a4 as Wn,a_ as Ca,as as nr,cn as w1,X as Ui,b7 as x1,b5 as S1,co as qp,bb as Af,cp as T1,aj as Jl,J as co,bc as I1,bf as E1,bg as A1,bp as M1,cq as Ei}from"./index-rD0Uu1v9.js";/*! +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-node-BIhtlSJe.js","assets/index-Dlp4W1Zl.js","assets/index-DIu27PLL.css","assets/import-url-browser-CPN8ipMD.js","assets/duckdb-mvp-CaaD-olE.js","assets/import-url-node-BfNoxhRr.js"])))=>i.map(i=>d[i]); +var f1=Object.defineProperty;var p1=(r,t,e)=>t in r?f1(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var W=(r,t,e)=>p1(r,typeof t!="symbol"?t+"":t,e);import{bm as If,ci as Dn,b2 as m1,a0 as g1,a9 as Fe,V as mt,Q as ne,a3 as Ps,ba as No,av as Hp,ag as Xp,ak as Yp,b3 as ec,b6 as Ef,cj as y1,$ as v1,ck as _1,a1 as b1,cl as Ho,cm as xn,W as qr,a4 as Wn,a_ as Ca,as as nr,cn as w1,X as Ui,b7 as x1,b5 as S1,co as qp,bb as Af,cp as T1,aj as Jl,J as co,bc as I1,bf as E1,bg as A1,bp as M1,cq as Ei}from"./index-Dlp4W1Zl.js";/*! * @pixi/constants - v6.5.10 * Compiled Thu, 06 Jul 2023 15:25:11 UTC * @@ -599,7 +599,7 @@ PERFORMANCE OF THIS SOFTWARE. Version 1.10.0 https://localforage.github.io/localForage (c) 2013-2017 Mozilla, Apache License 2.0 -*/var ig;function fM(){return ig||(ig=1,function(r,t){(function(e){r.exports=e()})(function(){return function e(n,i,s){function o(u,c){if(!i[u]){if(!n[u]){var h=typeof Ai=="function"&&Ai;if(!c&&h)return h(u,!0);if(a)return a(u,!0);var f=new Error("Cannot find module '"+u+"'");throw f.code="MODULE_NOT_FOUND",f}var d=i[u]={exports:{}};n[u][0].call(d.exports,function(m){var g=n[u][1][m];return o(g||m)},d,d.exports,e,n,i,s)}return i[u].exports}for(var a=typeof Ai=="function"&&Ai,l=0;l"u"&&e(3);var h=Promise;function f(A,V){V&&A.then(function(F){V(null,F)},function(F){V(F)})}function d(A,V,F){typeof V=="function"&&A.then(V),typeof F=="function"&&A.catch(F)}function m(A){return typeof A!="string"&&(console.warn(A+" used as a key, but it is not a string."),A=String(A)),A}function g(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var p="local-forage-detect-blob-support",y=void 0,_={},S=Object.prototype.toString,T="readonly",v="readwrite";function E(A){for(var V=A.length,F=new ArrayBuffer(V),X=new Uint8Array(F),J=0;J=43)}}).catch(function(){return!1})}function B(A){return typeof y=="boolean"?h.resolve(y):w(A).then(function(V){return y=V,y})}function N(A){var V=_[A.name],F={};F.promise=new h(function(X,J){F.resolve=X,F.reject=J}),V.deferredOperations.push(F),V.dbReady?V.dbReady=V.dbReady.then(function(){return F.promise}):V.dbReady=F.promise}function $(A){var V=_[A.name],F=V.deferredOperations.pop();if(F)return F.resolve(),F.promise}function it(A,V){var F=_[A.name],X=F.deferredOperations.pop();if(X)return X.reject(V),X.promise}function I(A,V){return new h(function(F,X){if(_[A.name]=_[A.name]||O(),A.db)if(V)N(A),A.db.close();else return F(A.db);var J=[A.name];V&&J.push(A.version);var G=l.open.apply(l,J);V&&(G.onupgradeneeded=function(st){var ut=G.result;try{ut.createObjectStore(A.storeName),st.oldVersion<=1&&ut.createObjectStore(p)}catch(dt){if(dt.name==="ConstraintError")console.warn('The database "'+A.name+'" has been upgraded from version '+st.oldVersion+" to version "+st.newVersion+', but the storage "'+A.storeName+'" already exists.');else throw dt}}),G.onerror=function(st){st.preventDefault(),X(G.error)},G.onsuccess=function(){var st=G.result;st.onversionchange=function(ut){ut.target.close()},F(st),$(A)}})}function Z(A){return I(A,!1)}function x(A){return I(A,!0)}function nt(A,V){if(!A.db)return!0;var F=!A.db.objectStoreNames.contains(A.storeName),X=A.versionA.db.version;if(X&&(A.version!==V&&console.warn('The database "'+A.name+`" can't be downgraded from version `+A.db.version+" to version "+A.version+"."),A.version=A.db.version),J||F){if(F){var G=A.db.version+1;G>A.version&&(A.version=G)}return!0}return!1}function P(A){return new h(function(V,F){var X=new FileReader;X.onerror=F,X.onloadend=function(J){var G=btoa(J.target.result||"");V({__local_forage_encoded_blob:!0,data:G,type:A.type})},X.readAsBinaryString(A)})}function C(A){var V=E(atob(A.data));return c([V],{type:A.type})}function R(A){return A&&A.__local_forage_encoded_blob}function z(A){var V=this,F=V._initReady().then(function(){var X=_[V._dbInfo.name];if(X&&X.dbReady)return X.dbReady});return d(F,A,A),F}function U(A){N(A);for(var V=_[A.name],F=V.forages,X=0;X0&&(!A.db||G.name==="InvalidStateError"||G.name==="NotFoundError"))return h.resolve().then(function(){if(!A.db||G.name==="NotFoundError"&&!A.db.objectStoreNames.contains(A.storeName)&&A.version<=A.db.version)return A.db&&(A.version=A.db.version+1),x(A)}).then(function(){return U(A).then(function(){M(A,V,F,X-1)})}).catch(F);F(G)}}function O(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function j(A){var V=this,F={db:null};if(A)for(var X in A)F[X]=A[X];var J=_[F.name];J||(J=O(),_[F.name]=J),J.forages.push(V),V._initReady||(V._initReady=V.ready,V.ready=z);var G=[];function st(){return h.resolve()}for(var ut=0;ut>4,yt[J++]=(st&15)<<4|ut>>2,yt[J++]=(ut&3)<<6|dt&63;return pt}function yn(A){var V=new Uint8Array(A),F="",X;for(X=0;X>2],F+=K[(V[X]&3)<<4|V[X+1]>>4],F+=K[(V[X+1]&15)<<2|V[X+2]>>6],F+=K[V[X+2]&63];return V.length%3===2?F=F.substring(0,F.length-1)+"=":V.length%3===1&&(F=F.substring(0,F.length-2)+"=="),F}function gi(A,V){var F="";if(A&&(F=ln.call(A)),A&&(F==="[object ArrayBuffer]"||A.buffer&&ln.call(A.buffer)==="[object ArrayBuffer]")){var X,J=D;A instanceof ArrayBuffer?(X=A,J+=ot):(X=A.buffer,F==="[object Int8Array]"?J+=rt:F==="[object Uint8Array]"?J+=ht:F==="[object Uint8ClampedArray]"?J+=wt:F==="[object Int16Array]"?J+=ft:F==="[object Uint16Array]"?J+=ge:F==="[object Int32Array]"?J+=Mt:F==="[object Uint32Array]"?J+=oe:F==="[object Float32Array]"?J+=Ke:F==="[object Float64Array]"?J+=sr:V(new Error("Failed to get type for BinaryArray"))),V(J+yn(X))}else if(F==="[object Blob]"){var G=new FileReader;G.onload=function(){var st=Q+A.type+"~"+yn(this.result);V(D+at+st)},G.readAsArrayBuffer(A)}else try{V(JSON.stringify(A))}catch(st){console.error("Couldn't convert value into a JSON string: ",A),V(null,st)}}function Ir(A){if(A.substring(0,q)!==D)return JSON.parse(A);var V=A.substring(cr),F=A.substring(q,cr),X;if(F===at&&L.test(V)){var J=V.match(L);X=J[1],V=V.substring(J[0].length)}var G=Ie(V);switch(F){case ot:return G;case at:return c([G],{type:X});case rt:return new Int8Array(G);case ht:return new Uint8Array(G);case wt:return new Uint8ClampedArray(G);case ft:return new Int16Array(G);case ge:return new Uint16Array(G);case Mt:return new Int32Array(G);case oe:return new Uint32Array(G);case Ke:return new Float32Array(G);case sr:return new Float64Array(G);default:throw new Error("Unkown type: "+F)}}var yi={serialize:gi,deserialize:Ir,stringToBuffer:Ie,bufferToString:yn};function Gi(A,V,F,X){A.executeSql("CREATE TABLE IF NOT EXISTS "+V.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],F,X)}function Vo(A){var V=this,F={db:null};if(A)for(var X in A)F[X]=typeof A[X]!="string"?A[X].toString():A[X];var J=new h(function(G,st){try{F.db=openDatabase(F.name,String(F.version),F.description,F.size)}catch(ut){return st(ut)}F.db.transaction(function(ut){Gi(ut,F,function(){V._dbInfo=F,G()},function(dt,pt){st(pt)})},st)});return F.serializer=yi,J}function kr(A,V,F,X,J,G){A.executeSql(F,X,J,function(st,ut){ut.code===ut.SYNTAX_ERR?st.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[V.storeName],function(dt,pt){pt.rows.length?G(dt,ut):Gi(dt,V,function(){dt.executeSql(F,X,J,G)},G)},G):G(st,ut)},G)}function Wi(A,V){var F=this;A=m(A);var X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"SELECT * FROM "+st.storeName+" WHERE key = ? LIMIT 1",[A],function(dt,pt){var yt=pt.rows.length?pt.rows.item(0).value:null;yt&&(yt=st.serializer.deserialize(yt)),J(yt)},function(dt,pt){G(pt)})})}).catch(G)});return f(X,V),X}function Yn(A,V){var F=this,X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"SELECT * FROM "+st.storeName,[],function(dt,pt){for(var yt=pt.rows,It=yt.length,ae=0;ae0){st(zr.apply(J,[A,dt,F,X-1]));return}ut(ae)}})})}).catch(ut)});return f(G,F),G}function Ns(A,V,F){return zr.apply(this,[A,V,F,1])}function sl(A,V){var F=this;A=m(A);var X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"DELETE FROM "+st.storeName+" WHERE key = ?",[A],function(){J()},function(dt,pt){G(pt)})})}).catch(G)});return f(X,V),X}function yc(A){var V=this,F=new h(function(X,J){V.ready().then(function(){var G=V._dbInfo;G.db.transaction(function(st){kr(st,G,"DELETE FROM "+G.storeName,[],function(){X()},function(ut,dt){J(dt)})})}).catch(J)});return f(F,A),F}function jo(A){var V=this,F=new h(function(X,J){V.ready().then(function(){var G=V._dbInfo;G.db.transaction(function(st){kr(st,G,"SELECT COUNT(key) as c FROM "+G.storeName,[],function(ut,dt){var pt=dt.rows.item(0).c;X(pt)},function(ut,dt){J(dt)})})}).catch(J)});return f(F,A),F}function vc(A,V){var F=this,X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"SELECT key FROM "+st.storeName+" WHERE id = ? LIMIT 1",[A+1],function(dt,pt){var yt=pt.rows.length?pt.rows.item(0).key:null;J(yt)},function(dt,pt){G(pt)})})}).catch(G)});return f(X,V),X}function _c(A){var V=this,F=new h(function(X,J){V.ready().then(function(){var G=V._dbInfo;G.db.transaction(function(st){kr(st,G,"SELECT key FROM "+G.storeName,[],function(ut,dt){for(var pt=[],yt=0;yt '__WebKitDatabaseInfoTable__'",[],function(J,G){for(var st=[],ut=0;ut0}function $o(A){var V=this,F={};if(A)for(var X in A)F[X]=A[X];return F.keyPrefix=al(A,V._defaultConfig),Tc()?(V._dbInfo=F,F.serializer=yi,h.resolve()):h.reject()}function ll(A){var V=this,F=V.ready().then(function(){for(var X=V._dbInfo.keyPrefix,J=localStorage.length-1;J>=0;J--){var G=localStorage.key(J);G.indexOf(X)===0&&localStorage.removeItem(G)}});return f(F,A),F}function Ic(A,V){var F=this;A=m(A);var X=F.ready().then(function(){var J=F._dbInfo,G=localStorage.getItem(J.keyPrefix+A);return G&&(G=J.serializer.deserialize(G)),G});return f(X,V),X}function Ec(A,V){var F=this,X=F.ready().then(function(){for(var J=F._dbInfo,G=J.keyPrefix,st=G.length,ut=localStorage.length,dt=1,pt=0;pt=0;st--){var ut=localStorage.key(st);ut.indexOf(G)===0&&localStorage.removeItem(ut)}}):J=h.reject("Invalid arguments"),f(J,V),J}var Oc={_driver:"localStorageWrapper",_initStorage:$o,_support:xc(),iterate:Ec,getItem:Ic,setItem:Cc,removeItem:Mc,clear:ll,length:ul,key:$p,keys:Ac,dropInstance:Bs},Pc=function(V,F){return V===F||typeof V=="number"&&typeof F=="number"&&isNaN(V)&&isNaN(F)},cl=function(V,F){for(var X=V.length,J=0;J"u"?"undefined":s(F))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var X in F){if(X==="storeName"&&(F[X]=F[X].replace(/\W/g,"_")),X==="version"&&typeof F[X]!="number")return new Error("Database version must be a number.");this._config[X]=F[X]}return"driver"in F&&F.driver?this.setDriver(this._config.driver):!0}else return typeof F=="string"?this._config[F]:this._config},A.prototype.defineDriver=function(F,X,J){var G=new h(function(st,ut){try{var dt=F._driver,pt=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!F._driver){ut(pt);return}for(var yt=Rc.concat("_initStorage"),It=0,ae=yt.length;It"u"&&e(3);var h=Promise;function f(A,V){V&&A.then(function(F){V(null,F)},function(F){V(F)})}function d(A,V,F){typeof V=="function"&&A.then(V),typeof F=="function"&&A.catch(F)}function m(A){return typeof A!="string"&&(console.warn(A+" used as a key, but it is not a string."),A=String(A)),A}function g(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var p="local-forage-detect-blob-support",y=void 0,_={},S=Object.prototype.toString,T="readonly",v="readwrite";function E(A){for(var V=A.length,F=new ArrayBuffer(V),X=new Uint8Array(F),J=0;J=43)}}).catch(function(){return!1})}function B(A){return typeof y=="boolean"?h.resolve(y):w(A).then(function(V){return y=V,y})}function N(A){var V=_[A.name],F={};F.promise=new h(function(X,J){F.resolve=X,F.reject=J}),V.deferredOperations.push(F),V.dbReady?V.dbReady=V.dbReady.then(function(){return F.promise}):V.dbReady=F.promise}function $(A){var V=_[A.name],F=V.deferredOperations.pop();if(F)return F.resolve(),F.promise}function it(A,V){var F=_[A.name],X=F.deferredOperations.pop();if(X)return X.reject(V),X.promise}function I(A,V){return new h(function(F,X){if(_[A.name]=_[A.name]||O(),A.db)if(V)N(A),A.db.close();else return F(A.db);var J=[A.name];V&&J.push(A.version);var G=l.open.apply(l,J);V&&(G.onupgradeneeded=function(st){var ut=G.result;try{ut.createObjectStore(A.storeName),st.oldVersion<=1&&ut.createObjectStore(p)}catch(dt){if(dt.name==="ConstraintError")console.warn('The database "'+A.name+'" has been upgraded from version '+st.oldVersion+" to version "+st.newVersion+', but the storage "'+A.storeName+'" already exists.');else throw dt}}),G.onerror=function(st){st.preventDefault(),X(G.error)},G.onsuccess=function(){var st=G.result;st.onversionchange=function(ut){ut.target.close()},F(st),$(A)}})}function Z(A){return I(A,!1)}function x(A){return I(A,!0)}function nt(A,V){if(!A.db)return!0;var F=!A.db.objectStoreNames.contains(A.storeName),X=A.versionA.db.version;if(X&&(A.version!==V&&console.warn('The database "'+A.name+`" can't be downgraded from version `+A.db.version+" to version "+A.version+"."),A.version=A.db.version),J||F){if(F){var G=A.db.version+1;G>A.version&&(A.version=G)}return!0}return!1}function P(A){return new h(function(V,F){var X=new FileReader;X.onerror=F,X.onloadend=function(J){var G=btoa(J.target.result||"");V({__local_forage_encoded_blob:!0,data:G,type:A.type})},X.readAsBinaryString(A)})}function C(A){var V=E(atob(A.data));return c([V],{type:A.type})}function R(A){return A&&A.__local_forage_encoded_blob}function z(A){var V=this,F=V._initReady().then(function(){var X=_[V._dbInfo.name];if(X&&X.dbReady)return X.dbReady});return d(F,A,A),F}function U(A){N(A);for(var V=_[A.name],F=V.forages,X=0;X0&&(!A.db||G.name==="InvalidStateError"||G.name==="NotFoundError"))return h.resolve().then(function(){if(!A.db||G.name==="NotFoundError"&&!A.db.objectStoreNames.contains(A.storeName)&&A.version<=A.db.version)return A.db&&(A.version=A.db.version+1),x(A)}).then(function(){return U(A).then(function(){M(A,V,F,X-1)})}).catch(F);F(G)}}function O(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function j(A){var V=this,F={db:null};if(A)for(var X in A)F[X]=A[X];var J=_[F.name];J||(J=O(),_[F.name]=J),J.forages.push(V),V._initReady||(V._initReady=V.ready,V.ready=z);var G=[];function st(){return h.resolve()}for(var ut=0;ut>4,yt[J++]=(st&15)<<4|ut>>2,yt[J++]=(ut&3)<<6|dt&63;return pt}function yn(A){var V=new Uint8Array(A),F="",X;for(X=0;X>2],F+=K[(V[X]&3)<<4|V[X+1]>>4],F+=K[(V[X+1]&15)<<2|V[X+2]>>6],F+=K[V[X+2]&63];return V.length%3===2?F=F.substring(0,F.length-1)+"=":V.length%3===1&&(F=F.substring(0,F.length-2)+"=="),F}function gi(A,V){var F="";if(A&&(F=ln.call(A)),A&&(F==="[object ArrayBuffer]"||A.buffer&&ln.call(A.buffer)==="[object ArrayBuffer]")){var X,J=D;A instanceof ArrayBuffer?(X=A,J+=ot):(X=A.buffer,F==="[object Int8Array]"?J+=rt:F==="[object Uint8Array]"?J+=ht:F==="[object Uint8ClampedArray]"?J+=wt:F==="[object Int16Array]"?J+=ft:F==="[object Uint16Array]"?J+=ge:F==="[object Int32Array]"?J+=Mt:F==="[object Uint32Array]"?J+=oe:F==="[object Float32Array]"?J+=Ke:F==="[object Float64Array]"?J+=sr:V(new Error("Failed to get type for BinaryArray"))),V(J+yn(X))}else if(F==="[object Blob]"){var G=new FileReader;G.onload=function(){var st=Q+A.type+"~"+yn(this.result);V(D+at+st)},G.readAsArrayBuffer(A)}else try{V(JSON.stringify(A))}catch(st){console.error("Couldn't convert value into a JSON string: ",A),V(null,st)}}function Ir(A){if(A.substring(0,q)!==D)return JSON.parse(A);var V=A.substring(cr),F=A.substring(q,cr),X;if(F===at&&L.test(V)){var J=V.match(L);X=J[1],V=V.substring(J[0].length)}var G=Ie(V);switch(F){case ot:return G;case at:return c([G],{type:X});case rt:return new Int8Array(G);case ht:return new Uint8Array(G);case wt:return new Uint8ClampedArray(G);case ft:return new Int16Array(G);case ge:return new Uint16Array(G);case Mt:return new Int32Array(G);case oe:return new Uint32Array(G);case Ke:return new Float32Array(G);case sr:return new Float64Array(G);default:throw new Error("Unkown type: "+F)}}var yi={serialize:gi,deserialize:Ir,stringToBuffer:Ie,bufferToString:yn};function Gi(A,V,F,X){A.executeSql("CREATE TABLE IF NOT EXISTS "+V.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],F,X)}function Vo(A){var V=this,F={db:null};if(A)for(var X in A)F[X]=typeof A[X]!="string"?A[X].toString():A[X];var J=new h(function(G,st){try{F.db=openDatabase(F.name,String(F.version),F.description,F.size)}catch(ut){return st(ut)}F.db.transaction(function(ut){Gi(ut,F,function(){V._dbInfo=F,G()},function(dt,pt){st(pt)})},st)});return F.serializer=yi,J}function kr(A,V,F,X,J,G){A.executeSql(F,X,J,function(st,ut){ut.code===ut.SYNTAX_ERR?st.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[V.storeName],function(dt,pt){pt.rows.length?G(dt,ut):Gi(dt,V,function(){dt.executeSql(F,X,J,G)},G)},G):G(st,ut)},G)}function Wi(A,V){var F=this;A=m(A);var X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"SELECT * FROM "+st.storeName+" WHERE key = ? LIMIT 1",[A],function(dt,pt){var yt=pt.rows.length?pt.rows.item(0).value:null;yt&&(yt=st.serializer.deserialize(yt)),J(yt)},function(dt,pt){G(pt)})})}).catch(G)});return f(X,V),X}function Yn(A,V){var F=this,X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"SELECT * FROM "+st.storeName,[],function(dt,pt){for(var yt=pt.rows,Tt=yt.length,ae=0;ae0){st(zr.apply(J,[A,dt,F,X-1]));return}ut(ae)}})})}).catch(ut)});return f(G,F),G}function Ns(A,V,F){return zr.apply(this,[A,V,F,1])}function sl(A,V){var F=this;A=m(A);var X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"DELETE FROM "+st.storeName+" WHERE key = ?",[A],function(){J()},function(dt,pt){G(pt)})})}).catch(G)});return f(X,V),X}function yc(A){var V=this,F=new h(function(X,J){V.ready().then(function(){var G=V._dbInfo;G.db.transaction(function(st){kr(st,G,"DELETE FROM "+G.storeName,[],function(){X()},function(ut,dt){J(dt)})})}).catch(J)});return f(F,A),F}function jo(A){var V=this,F=new h(function(X,J){V.ready().then(function(){var G=V._dbInfo;G.db.transaction(function(st){kr(st,G,"SELECT COUNT(key) as c FROM "+G.storeName,[],function(ut,dt){var pt=dt.rows.item(0).c;X(pt)},function(ut,dt){J(dt)})})}).catch(J)});return f(F,A),F}function vc(A,V){var F=this,X=new h(function(J,G){F.ready().then(function(){var st=F._dbInfo;st.db.transaction(function(ut){kr(ut,st,"SELECT key FROM "+st.storeName+" WHERE id = ? LIMIT 1",[A+1],function(dt,pt){var yt=pt.rows.length?pt.rows.item(0).key:null;J(yt)},function(dt,pt){G(pt)})})}).catch(G)});return f(X,V),X}function _c(A){var V=this,F=new h(function(X,J){V.ready().then(function(){var G=V._dbInfo;G.db.transaction(function(st){kr(st,G,"SELECT key FROM "+G.storeName,[],function(ut,dt){for(var pt=[],yt=0;yt '__WebKitDatabaseInfoTable__'",[],function(J,G){for(var st=[],ut=0;ut0}function $o(A){var V=this,F={};if(A)for(var X in A)F[X]=A[X];return F.keyPrefix=al(A,V._defaultConfig),Tc()?(V._dbInfo=F,F.serializer=yi,h.resolve()):h.reject()}function ll(A){var V=this,F=V.ready().then(function(){for(var X=V._dbInfo.keyPrefix,J=localStorage.length-1;J>=0;J--){var G=localStorage.key(J);G.indexOf(X)===0&&localStorage.removeItem(G)}});return f(F,A),F}function Ic(A,V){var F=this;A=m(A);var X=F.ready().then(function(){var J=F._dbInfo,G=localStorage.getItem(J.keyPrefix+A);return G&&(G=J.serializer.deserialize(G)),G});return f(X,V),X}function Ec(A,V){var F=this,X=F.ready().then(function(){for(var J=F._dbInfo,G=J.keyPrefix,st=G.length,ut=localStorage.length,dt=1,pt=0;pt=0;st--){var ut=localStorage.key(st);ut.indexOf(G)===0&&localStorage.removeItem(ut)}}):J=h.reject("Invalid arguments"),f(J,V),J}var Oc={_driver:"localStorageWrapper",_initStorage:$o,_support:xc(),iterate:Ec,getItem:Ic,setItem:Cc,removeItem:Mc,clear:ll,length:ul,key:$p,keys:Ac,dropInstance:Bs},Pc=function(V,F){return V===F||typeof V=="number"&&typeof F=="number"&&isNaN(V)&&isNaN(F)},cl=function(V,F){for(var X=V.length,J=0;J"u"?"undefined":s(F))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var X in F){if(X==="storeName"&&(F[X]=F[X].replace(/\W/g,"_")),X==="version"&&typeof F[X]!="number")return new Error("Database version must be a number.");this._config[X]=F[X]}return"driver"in F&&F.driver?this.setDriver(this._config.driver):!0}else return typeof F=="string"?this._config[F]:this._config},A.prototype.defineDriver=function(F,X,J){var G=new h(function(st,ut){try{var dt=F._driver,pt=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!F._driver){ut(pt);return}for(var yt=Rc.concat("_initStorage"),Tt=0,ae=yt.length;Tt=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rt(r){return this instanceof Rt?(this.v=r,this):new Rt(r)}function br(r,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=e.apply(r,t||[]),i,s=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(d){return function(m){return Promise.resolve(m).then(d,h)}}function a(d,m){n[d]&&(i[d]=function(g){return new Promise(function(p,y){s.push([d,g,p,y])>1||l(d,g)})},m&&(i[d]=m(i[d])))}function l(d,m){try{u(n[d](m))}catch(g){f(s[0][3],g)}}function u(d){d.value instanceof Rt?Promise.resolve(d.value.v).then(c,h):f(s[0][2],d)}function c(d){l("next",d)}function h(d){l("throw",d)}function f(d,m){d(m),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Ss(r){var t,e;return t={},n("next"),n("throw",function(i){throw i}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(i,s){t[i]=r[i]?function(o){return(e=!e)?{value:Rt(r[i](o)),done:!1}:s?s(o):o}:s}}function Bn(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=r[Symbol.asyncIterator],e;return t?t.call(r):(r=typeof Qg=="function"?Qg(r):r[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(s){e[s]=r[s]&&function(o){return new Promise(function(a,l){o=r[s](o),i(a,l,o.done,o.value)})}}function i(s,o,a,l){Promise.resolve(l).then(function(u){s({value:u,done:a})},o)}}const VR=new TextDecoder("utf-8"),Wd=r=>VR.decode(r),jR=new TextEncoder,Qf=r=>jR.encode(r),$R=r=>typeof r=="number",Pb=r=>typeof r=="boolean",Ye=r=>typeof r=="function",wr=r=>r!=null&&Object(r)===r,Is=r=>wr(r)&&Ye(r.then),Qa=r=>wr(r)&&Ye(r[Symbol.iterator]),Uo=r=>wr(r)&&Ye(r[Symbol.asyncIterator]),Hd=r=>wr(r)&&wr(r.schema),Rb=r=>wr(r)&&"done"in r&&"value"in r,Fb=r=>wr(r)&&Ye(r.stat)&&$R(r.fd),Db=r=>wr(r)&&Zf(r.body),oc=r=>"_getDOMStream"in r&&"_getNodeStream"in r,GR=r=>wr(r)&&Ye(r.abort)&&Ye(r.getWriter)&&!oc(r),Zf=r=>wr(r)&&Ye(r.cancel)&&Ye(r.getReader)&&!oc(r),WR=r=>wr(r)&&Ye(r.end)&&Ye(r.write)&&Pb(r.writable)&&!oc(r),Lb=r=>wr(r)&&Ye(r.read)&&Ye(r.pipe)&&Pb(r.readable)&&!oc(r),HR=r=>wr(r)&&Ye(r.clear)&&Ye(r.bytes)&&Ye(r.position)&&Ye(r.setPosition)&&Ye(r.capacity)&&Ye(r.getBufferIdentifier)&&Ye(r.createLong),Kf=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function XR(r){const t=r[0]?[r[0]]:[];let e,n,i,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let i,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,n);for(const c=e.length;++lxe(Int32Array,r),Kg=r=>xe(BigInt64Array,r),ce=r=>xe(Uint8Array,r),Xd=r=>(r.next(),r);function*YR(r,t){const e=function*(i){yield i},n=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof Kf?e(t):Qa(t)?t:e(t);return yield*Xd(function*(i){let s=null;do s=i.next(yield xe(r,s));while(!s.done)}(n[Symbol.iterator]())),new r}const qR=r=>YR(Uint8Array,r);function Nb(r,t){return br(this,arguments,function*(){if(Is(t))return yield Rt(yield Rt(yield*Ss(Bn(Nb(r,yield Rt(t))))));const n=function(o){return br(this,arguments,function*(){yield yield Rt(yield Rt(o))})},i=function(o){return br(this,arguments,function*(){yield Rt(yield*Ss(Bn(Xd(function*(a){let l=null;do l=a.next(yield l==null?void 0:l.value);while(!l.done)}(o[Symbol.iterator]())))))})},s=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof Kf?n(t):Qa(t)?i(t):Uo(t)?t:n(t);return yield Rt(yield*Ss(Bn(Xd(function(o){return br(this,arguments,function*(){let a=null;do a=yield Rt(o.next(yield yield Rt(xe(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Rt(new r)})}const QR=r=>Nb(Uint8Array,r);function Bb(r,t,e){if(r!==0){e=e.slice(0,t);for(let n=-1,i=e.length;++n0)do if(r[e]!==t[e])return!1;while(++e(r.next(),r);function*KR(r){let t,e=!1,n=[],i,s,o,a=0;function l(){return s==="peek"?kn(n,o)[0]:([i,n,a]=kn(n,o),i)}({cmd:s,size:o}=(yield null)||{cmd:"read",size:0});const u=qR(r)[Symbol.iterator]();try{do if({done:t,value:i}=Number.isNaN(o-a)?u.next():u.next(o-a),!t&&i.byteLength>0&&(n.push(i),a+=i.byteLength),t||o<=a)do({cmd:s,size:o}=yield l());while(o0&&(i.push(s),l+=s.byteLength),e||a<=l)do({cmd:o,size:a}=yield yield Rt(u()));while(a0&&(i.push(ce(s)),l+=s.byteLength),e||a<=l)do({cmd:o,size:a}=yield yield Rt(u()));while(a{})}get closed(){return this.reader?this.reader.closed.catch(()=>{}):Promise.resolve()}releaseLock(){this.reader&&this.reader.releaseLock(),this.reader=null}cancel(t){return Jt(this,void 0,void 0,function*(){const{reader:e,source:n}=this;e&&(yield e.cancel(t).catch(()=>{})),n&&n.locked&&this.releaseLock()})}read(t){return Jt(this,void 0,void 0,function*(){if(t===0)return{done:this.reader==null,value:new Uint8Array(0)};const e=yield this.reader.read();return!e.done&&(e.value=ce(e)),e})}}const Ah=(r,t)=>{const e=i=>n([t,i]);let n;return[t,e,new Promise(i=>(n=i)&&r.once(t,e))]};function rF(r){return br(this,arguments,function*(){const e=[];let n="error",i=!1,s=null,o,a,l=0,u=[],c;function h(){return o==="peek"?kn(u,a)[0]:([c,u,l]=kn(u,a),c)}if({cmd:o,size:a}=(yield yield Rt(null))||{cmd:"read",size:0},r.isTTY)return yield yield Rt(new Uint8Array(0)),yield Rt(null);try{e[0]=Ah(r,"end"),e[1]=Ah(r,"error");do{if(e[2]=Ah(r,"readable"),[n,s]=yield Rt(Promise.race(e.map(d=>d[2]))),n==="error")break;if((i=n==="end")||(Number.isFinite(a-l)?(c=ce(r.read(a-l)),c.byteLength0&&(u.push(c),l+=c.byteLength)),i||a<=l)do({cmd:o,size:a}=yield yield Rt(h()));while(a{for(const[y,_]of d)r.off(y,_);try{const y=r.destroy;y&&y.call(r,m),m=void 0}catch(y){m=y||m}finally{m!=null?p(m):g()}})}})}var je;(function(r){r[r.V1=0]="V1",r[r.V2=1]="V2",r[r.V3=2]="V3",r[r.V4=3]="V4",r[r.V5=4]="V5"})(je||(je={}));var lr;(function(r){r[r.Sparse=0]="Sparse",r[r.Dense=1]="Dense"})(lr||(lr={}));var ar;(function(r){r[r.HALF=0]="HALF",r[r.SINGLE=1]="SINGLE",r[r.DOUBLE=2]="DOUBLE"})(ar||(ar={}));var nn;(function(r){r[r.DAY=0]="DAY",r[r.MILLISECOND=1]="MILLISECOND"})(nn||(nn={}));var Vt;(function(r){r[r.SECOND=0]="SECOND",r[r.MILLISECOND=1]="MILLISECOND",r[r.MICROSECOND=2]="MICROSECOND",r[r.NANOSECOND=3]="NANOSECOND"})(Vt||(Vt={}));var zn;(function(r){r[r.YEAR_MONTH=0]="YEAR_MONTH",r[r.DAY_TIME=1]="DAY_TIME",r[r.MONTH_DAY_NANO=2]="MONTH_DAY_NANO"})(zn||(zn={}));const Mh=2,Pn=4,oi=4,_e=4,Ti=new Int32Array(2),Jg=new Float32Array(Ti.buffer),ty=new Float64Array(Ti.buffer),Dl=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Yd;(function(r){r[r.UTF8_BYTES=1]="UTF8_BYTES",r[r.UTF16_STRING=2]="UTF16_STRING"})(Yd||(Yd={}));let Mo=class Ub{constructor(t){this.bytes_=t,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new Ub(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(t){this.position_=t}capacity(){return this.bytes_.length}readInt8(t){return this.readUint8(t)<<24>>24}readUint8(t){return this.bytes_[t]}readInt16(t){return this.readUint16(t)<<16>>16}readUint16(t){return this.bytes_[t]|this.bytes_[t+1]<<8}readInt32(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24}readUint32(t){return this.readInt32(t)>>>0}readInt64(t){return BigInt.asIntN(64,BigInt(this.readUint32(t))+(BigInt(this.readUint32(t+4))<>8}writeUint16(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8}writeInt32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeUint32(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24}writeInt64(t,e){this.writeInt32(t,Number(BigInt.asIntN(32,e))),this.writeInt32(t+4,Number(BigInt.asIntN(32,e>>BigInt(32))))}writeUint64(t,e){this.writeUint32(t,Number(BigInt.asUintN(32,e))),this.writeUint32(t+4,Number(BigInt.asUintN(32,e>>BigInt(32))))}writeFloat32(t,e){Jg[0]=e,this.writeInt32(t,Ti[0])}writeFloat64(t,e){ty[0]=e,this.writeInt32(t,Ti[Dl?0:1]),this.writeInt32(t+4,Ti[Dl?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=t);const n=~(this.bb.capacity()-this.space+e)+1&t-1;for(;this.space=0&&this.vtable[e]==0;e--);const n=e+1;for(;e>=0;e--)this.addInt16(this.vtable[e]!=0?t-this.vtable[e]:0);const i=2;this.addInt16(t-this.object_start);const s=(n+i)*Mh;this.addInt16(s);let o=0;const a=this.space;t:for(e=0;e=0;o--)this.writeInt8(s.charCodeAt(o))}this.prep(this.minalign,Pn+i),this.addOffset(t),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const n=this.bb.capacity()-t,i=n-this.bb.readInt32(n);if(!(e=0;n--)t.addInt32(e[n]);return t.endVector()}static startTypeIdsVector(t,e){t.startVector(4,e,4)}static endUnion(t){return t.endObject()}static createUnion(t,e,n){return vr.startUnion(t),vr.addMode(t,e),vr.addTypeIds(t,n),vr.endUnion(t)}}let ay=class _a{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsUtf8(t,e){return(e||new _a).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUtf8(t,e){return t.setPosition(t.position()+_e),(e||new _a).__init(t.readInt32(t.position())+t.position(),t)}static startUtf8(t){t.startObject(0)}static endUtf8(t){return t.endObject()}static createUtf8(t){return _a.startUtf8(t),_a.endUtf8(t)}};var Ee;(function(r){r[r.NONE=0]="NONE",r[r.Null=1]="Null",r[r.Int=2]="Int",r[r.FloatingPoint=3]="FloatingPoint",r[r.Binary=4]="Binary",r[r.Utf8=5]="Utf8",r[r.Bool=6]="Bool",r[r.Decimal=7]="Decimal",r[r.Date=8]="Date",r[r.Time=9]="Time",r[r.Timestamp=10]="Timestamp",r[r.Interval=11]="Interval",r[r.List=12]="List",r[r.Struct_=13]="Struct_",r[r.Union=14]="Union",r[r.FixedSizeBinary=15]="FixedSizeBinary",r[r.FixedSizeList=16]="FixedSizeList",r[r.Map=17]="Map",r[r.Duration=18]="Duration",r[r.LargeBinary=19]="LargeBinary",r[r.LargeUtf8=20]="LargeUtf8",r[r.LargeList=21]="LargeList",r[r.RunEndEncoded=22]="RunEndEncoded"})(Ee||(Ee={}));let Wr=class Hl{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsField(t,e){return(e||new Hl).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsField(t,e){return t.setPosition(t.position()+_e),(e||new Hl).__init(t.readInt32(t.position())+t.position(),t)}name(t){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}nullable(){const t=this.bb.__offset(this.bb_pos,6);return t?!!this.bb.readInt8(this.bb_pos+t):!1}typeType(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readUint8(this.bb_pos+t):Ee.NONE}type(t){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__union(t,this.bb_pos+e):null}dictionary(t){const e=this.bb.__offset(this.bb_pos,12);return e?(t||new ai).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}children(t,e){const n=this.bb.__offset(this.bb_pos,14);return n?(e||new Hl).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}childrenLength(){const t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}customMetadata(t,e){const n=this.bb.__offset(this.bb_pos,16);return n?(e||new qe).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}customMetadataLength(){const t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}static startField(t){t.startObject(7)}static addName(t,e){t.addFieldOffset(0,e,0)}static addNullable(t,e){t.addFieldInt8(1,+e,0)}static addTypeType(t,e){t.addFieldInt8(2,e,Ee.NONE)}static addType(t,e){t.addFieldOffset(3,e,0)}static addDictionary(t,e){t.addFieldOffset(4,e,0)}static addChildren(t,e){t.addFieldOffset(5,e,0)}static createChildrenVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startChildrenVector(t,e){t.startVector(4,e,4)}static addCustomMetadata(t,e){t.addFieldOffset(6,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endField(t){return t.endObject()}},In=class Zn{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSchema(t,e){return(e||new Zn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSchema(t,e){return t.setPosition(t.position()+_e),(e||new Zn).__init(t.readInt32(t.position())+t.position(),t)}endianness(){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):Co.Little}fields(t,e){const n=this.bb.__offset(this.bb_pos,6);return n?(e||new Wr).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}fieldsLength(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}customMetadata(t,e){const n=this.bb.__offset(this.bb_pos,8);return n?(e||new qe).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}customMetadataLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}features(t){const e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+t*8):BigInt(0)}featuresLength(){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSchema(t){t.startObject(4)}static addEndianness(t,e){t.addFieldInt16(0,e,Co.Little)}static addFields(t,e){t.addFieldOffset(1,e,0)}static createFieldsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startFieldsVector(t,e){t.startVector(4,e,4)}static addCustomMetadata(t,e){t.addFieldOffset(2,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static addFeatures(t,e){t.addFieldOffset(3,e,0)}static createFeaturesVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startFeaturesVector(t,e){t.startVector(8,e,8)}static endSchema(t){return t.endObject()}static finishSchemaBuffer(t,e){t.finish(e)}static finishSizePrefixedSchemaBuffer(t,e){t.finish(e,void 0,!0)}static createSchema(t,e,n,i,s){return Zn.startSchema(t),Zn.addEndianness(t,e),Zn.addFields(t,n),Zn.addCustomMetadata(t,i),Zn.addFeatures(t,s),Zn.endSchema(t)}};var me;(function(r){r[r.NONE=0]="NONE",r[r.Schema=1]="Schema",r[r.DictionaryBatch=2]="DictionaryBatch",r[r.RecordBatch=3]="RecordBatch",r[r.Tensor=4]="Tensor",r[r.SparseTensor=5]="SparseTensor"})(me||(me={}));var k;(function(r){r[r.NONE=0]="NONE",r[r.Null=1]="Null",r[r.Int=2]="Int",r[r.Float=3]="Float",r[r.Binary=4]="Binary",r[r.Utf8=5]="Utf8",r[r.Bool=6]="Bool",r[r.Decimal=7]="Decimal",r[r.Date=8]="Date",r[r.Time=9]="Time",r[r.Timestamp=10]="Timestamp",r[r.Interval=11]="Interval",r[r.List=12]="List",r[r.Struct=13]="Struct",r[r.Union=14]="Union",r[r.FixedSizeBinary=15]="FixedSizeBinary",r[r.FixedSizeList=16]="FixedSizeList",r[r.Map=17]="Map",r[r.Duration=18]="Duration",r[r.LargeBinary=19]="LargeBinary",r[r.LargeUtf8=20]="LargeUtf8",r[r.Dictionary=-1]="Dictionary",r[r.Int8=-2]="Int8",r[r.Int16=-3]="Int16",r[r.Int32=-4]="Int32",r[r.Int64=-5]="Int64",r[r.Uint8=-6]="Uint8",r[r.Uint16=-7]="Uint16",r[r.Uint32=-8]="Uint32",r[r.Uint64=-9]="Uint64",r[r.Float16=-10]="Float16",r[r.Float32=-11]="Float32",r[r.Float64=-12]="Float64",r[r.DateDay=-13]="DateDay",r[r.DateMillisecond=-14]="DateMillisecond",r[r.TimestampSecond=-15]="TimestampSecond",r[r.TimestampMillisecond=-16]="TimestampMillisecond",r[r.TimestampMicrosecond=-17]="TimestampMicrosecond",r[r.TimestampNanosecond=-18]="TimestampNanosecond",r[r.TimeSecond=-19]="TimeSecond",r[r.TimeMillisecond=-20]="TimeMillisecond",r[r.TimeMicrosecond=-21]="TimeMicrosecond",r[r.TimeNanosecond=-22]="TimeNanosecond",r[r.DenseUnion=-23]="DenseUnion",r[r.SparseUnion=-24]="SparseUnion",r[r.IntervalDayTime=-25]="IntervalDayTime",r[r.IntervalYearMonth=-26]="IntervalYearMonth",r[r.DurationSecond=-27]="DurationSecond",r[r.DurationMillisecond=-28]="DurationMillisecond",r[r.DurationMicrosecond=-29]="DurationMicrosecond",r[r.DurationNanosecond=-30]="DurationNanosecond"})(k||(k={}));var ni;(function(r){r[r.OFFSET=0]="OFFSET",r[r.DATA=1]="DATA",r[r.VALIDITY=2]="VALIDITY",r[r.TYPE=3]="TYPE"})(ni||(ni={}));const nF=void 0;function Ba(r){if(r===null)return"null";if(r===nF)return"undefined";switch(typeof r){case"number":return`${r}`;case"bigint":return`${r}`;case"string":return`"${r}"`}return typeof r[Symbol.toPrimitive]=="function"?r[Symbol.toPrimitive]("string"):ArrayBuffer.isView(r)?r instanceof BigInt64Array||r instanceof BigUint64Array?`[${[...r].map(t=>Ba(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}function Te(r){if(typeof r=="bigint"&&(rNumber.MAX_SAFE_INTEGER))throw new TypeError(`${r} is not safe to convert to a number.`);return Number(r)}function $b(r,t){return Te(r/t)+Te(r%t)/Te(t)}const iF=Symbol.for("isArrowBigNum");function pn(r,...t){return t.length===0?Object.setPrototypeOf(xe(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}pn.prototype[iF]=!0;pn.prototype.toJSON=function(){return`"${ka(this)}"`};pn.prototype.valueOf=function(r){return Gb(this,r)};pn.prototype.toString=function(){return ka(this)};pn.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Gb(this);case"string":return ka(this);case"default":return aF(this)}return ka(this)};function vo(...r){return pn.apply(this,r)}function _o(...r){return pn.apply(this,r)}function Ua(...r){return pn.apply(this,r)}Object.setPrototypeOf(vo.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(_o.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Ua.prototype,Object.create(Uint32Array.prototype));Object.assign(vo.prototype,pn.prototype,{constructor:vo,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(_o.prototype,pn.prototype,{constructor:_o,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Ua.prototype,pn.prototype,{constructor:Ua,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const sF=BigInt(4294967296)*BigInt(4294967296),oF=sF-BigInt(1);function Gb(r,t){const{buffer:e,byteOffset:n,byteLength:i,signed:s}=r,o=new BigUint64Array(e,n,i/8),a=s&&o.at(-1)&BigInt(1)<=0)return Ch(r);t=t.slice();let n=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(Ot.prototype);let Ri=class extends Ot{constructor(){super(k.Null)}toString(){return"Null"}};Xb=Symbol.toStringTag;Ri[Xb]=(r=>r[Symbol.toStringTag]="Null")(Ri.prototype);let Es=class extends Ot{constructor(t,e){super(k.Int),this.isSigned=t,this.bitWidth=e}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}};Yb=Symbol.toStringTag;Es[Yb]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))(Es.prototype);class za extends Es{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(za.prototype,"ArrayType",{value:Int32Array});let mu=class extends Ot{constructor(t){super(k.Float),this.precision=t}get ArrayType(){switch(this.precision){case ar.HALF:return Uint16Array;case ar.SINGLE:return Float32Array;case ar.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}};qb=Symbol.toStringTag;mu[qb]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(mu.prototype);let gu=class extends Ot{constructor(){super(k.Binary)}toString(){return"Binary"}};Qb=Symbol.toStringTag;gu[Qb]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(gu.prototype);let yu=class extends Ot{constructor(){super(k.LargeBinary)}toString(){return"LargeBinary"}};Zb=Symbol.toStringTag;yu[Zb]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(yu.prototype);let vu=class extends Ot{constructor(){super(k.Utf8)}toString(){return"Utf8"}};Kb=Symbol.toStringTag;vu[Kb]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(vu.prototype);let _u=class extends Ot{constructor(){super(k.LargeUtf8)}toString(){return"LargeUtf8"}};Jb=Symbol.toStringTag;_u[Jb]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(_u.prototype);let bu=class extends Ot{constructor(){super(k.Bool)}toString(){return"Bool"}};tw=Symbol.toStringTag;bu[tw]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(bu.prototype);let wu=class extends Ot{constructor(t,e,n=128){super(k.Decimal),this.scale=t,this.precision=e,this.bitWidth=n}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}};ew=Symbol.toStringTag;wu[ew]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(wu.prototype);let xu=class extends Ot{constructor(t){super(k.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${nn[this.unit]}>`}get ArrayType(){return this.unit===nn.DAY?Int32Array:BigInt64Array}};rw=Symbol.toStringTag;xu[rw]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(xu.prototype);let Su=class extends Ot{constructor(t,e){super(k.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${Vt[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}};nw=Symbol.toStringTag;Su[nw]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(Su.prototype);let Tu=class extends Ot{constructor(t,e){super(k.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${Vt[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}};iw=Symbol.toStringTag;Tu[iw]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(Tu.prototype);let Iu=class extends Ot{constructor(t){super(k.Interval),this.unit=t}toString(){return`Interval<${zn[this.unit]}>`}};sw=Symbol.toStringTag;Iu[sw]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(Iu.prototype);let Eu=class extends Ot{constructor(t){super(k.Duration),this.unit=t}toString(){return`Duration<${Vt[this.unit]}>`}};ow=Symbol.toStringTag;Eu[ow]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(Eu.prototype);let Au=class extends Ot{constructor(t){super(k.List),this.children=[t]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}};aw=Symbol.toStringTag;Au[aw]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(Au.prototype);let dr=class extends Ot{constructor(t){super(k.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}};lw=Symbol.toStringTag;dr[lw]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(dr.prototype);let Mu=class extends Ot{constructor(t,e,n){super(k.Union),this.mode=t,this.children=n,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((i,s,o)=>(i[s]=o)&&i||i,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}};uw=Symbol.toStringTag;Mu[uw]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))(Mu.prototype);let Cu=class extends Ot{constructor(t){super(k.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}};cw=Symbol.toStringTag;Cu[cw]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(Cu.prototype);let Ou=class extends Ot{constructor(t,e){super(k.FixedSizeList),this.listSize=t,this.children=[e]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}};hw=Symbol.toStringTag;Ou[hw]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(Ou.prototype);let Pu=class extends Ot{constructor(t,e=!1){var n,i,s;if(super(k.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((n=t==null?void 0:t.type)===null||n===void 0)&&n.children)){const o=(i=t==null?void 0:t.type)===null||i===void 0?void 0:i.children[0];o&&(o.name="key");const a=(s=t==null?void 0:t.type)===null||s===void 0?void 0:s.children[1];a&&(a.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}};dw=Symbol.toStringTag;Pu[dw]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(Pu.prototype);const uF=(r=>()=>++r)(-1);let Oo=class extends Ot{constructor(t,e,n,i){super(k.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=i||!1,this.id=n==null?uF():Te(n)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}};fw=Symbol.toStringTag;Oo[fw]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(Oo.prototype);function ii(r){const t=r;switch(r.typeId){case k.Decimal:return r.bitWidth/32;case k.Interval:return 1+t.unit;case k.FixedSizeList:return t.listSize;case k.FixedSizeBinary:return t.byteWidth;default:return 1}}let se=class{visitMany(t,...e){return t.map((n,i)=>this.visit(n,...e.map(s=>s[i])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return cF(this,t,e)}getVisitFnByTypeId(t,e=!0){return io(this,t,e)}visitNull(t,...e){return null}visitBool(t,...e){return null}visitInt(t,...e){return null}visitFloat(t,...e){return null}visitUtf8(t,...e){return null}visitLargeUtf8(t,...e){return null}visitBinary(t,...e){return null}visitLargeBinary(t,...e){return null}visitFixedSizeBinary(t,...e){return null}visitDate(t,...e){return null}visitTimestamp(t,...e){return null}visitTime(t,...e){return null}visitDecimal(t,...e){return null}visitList(t,...e){return null}visitStruct(t,...e){return null}visitUnion(t,...e){return null}visitDictionary(t,...e){return null}visitInterval(t,...e){return null}visitDuration(t,...e){return null}visitFixedSizeList(t,...e){return null}visitMap(t,...e){return null}};function cF(r,t,e=!0){return typeof t=="number"?io(r,t,e):typeof t=="string"&&t in k?io(r,k[t],e):t&&t instanceof Ot?io(r,ly(t),e):t!=null&&t.type&&t.type instanceof Ot?io(r,ly(t.type),e):io(r,k.NONE,e)}function io(r,t,e=!0){let n=null;switch(t){case k.Null:n=r.visitNull;break;case k.Bool:n=r.visitBool;break;case k.Int:n=r.visitInt;break;case k.Int8:n=r.visitInt8||r.visitInt;break;case k.Int16:n=r.visitInt16||r.visitInt;break;case k.Int32:n=r.visitInt32||r.visitInt;break;case k.Int64:n=r.visitInt64||r.visitInt;break;case k.Uint8:n=r.visitUint8||r.visitInt;break;case k.Uint16:n=r.visitUint16||r.visitInt;break;case k.Uint32:n=r.visitUint32||r.visitInt;break;case k.Uint64:n=r.visitUint64||r.visitInt;break;case k.Float:n=r.visitFloat;break;case k.Float16:n=r.visitFloat16||r.visitFloat;break;case k.Float32:n=r.visitFloat32||r.visitFloat;break;case k.Float64:n=r.visitFloat64||r.visitFloat;break;case k.Utf8:n=r.visitUtf8;break;case k.LargeUtf8:n=r.visitLargeUtf8;break;case k.Binary:n=r.visitBinary;break;case k.LargeBinary:n=r.visitLargeBinary;break;case k.FixedSizeBinary:n=r.visitFixedSizeBinary;break;case k.Date:n=r.visitDate;break;case k.DateDay:n=r.visitDateDay||r.visitDate;break;case k.DateMillisecond:n=r.visitDateMillisecond||r.visitDate;break;case k.Timestamp:n=r.visitTimestamp;break;case k.TimestampSecond:n=r.visitTimestampSecond||r.visitTimestamp;break;case k.TimestampMillisecond:n=r.visitTimestampMillisecond||r.visitTimestamp;break;case k.TimestampMicrosecond:n=r.visitTimestampMicrosecond||r.visitTimestamp;break;case k.TimestampNanosecond:n=r.visitTimestampNanosecond||r.visitTimestamp;break;case k.Time:n=r.visitTime;break;case k.TimeSecond:n=r.visitTimeSecond||r.visitTime;break;case k.TimeMillisecond:n=r.visitTimeMillisecond||r.visitTime;break;case k.TimeMicrosecond:n=r.visitTimeMicrosecond||r.visitTime;break;case k.TimeNanosecond:n=r.visitTimeNanosecond||r.visitTime;break;case k.Decimal:n=r.visitDecimal;break;case k.List:n=r.visitList;break;case k.Struct:n=r.visitStruct;break;case k.Union:n=r.visitUnion;break;case k.DenseUnion:n=r.visitDenseUnion||r.visitUnion;break;case k.SparseUnion:n=r.visitSparseUnion||r.visitUnion;break;case k.Dictionary:n=r.visitDictionary;break;case k.Interval:n=r.visitInterval;break;case k.IntervalDayTime:n=r.visitIntervalDayTime||r.visitInterval;break;case k.IntervalYearMonth:n=r.visitIntervalYearMonth||r.visitInterval;break;case k.Duration:n=r.visitDuration;break;case k.DurationSecond:n=r.visitDurationSecond||r.visitDuration;break;case k.DurationMillisecond:n=r.visitDurationMillisecond||r.visitDuration;break;case k.DurationMicrosecond:n=r.visitDurationMicrosecond||r.visitDuration;break;case k.DurationNanosecond:n=r.visitDurationNanosecond||r.visitDuration;break;case k.FixedSizeList:n=r.visitFixedSizeList;break;case k.Map:n=r.visitMap;break}if(typeof n=="function")return n;if(!e)return()=>null;throw new Error(`Unrecognized type '${k[t]}'`)}function ly(r){switch(r.typeId){case k.Null:return k.Null;case k.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?k.Int8:k.Uint8;case 16:return e?k.Int16:k.Uint16;case 32:return e?k.Int32:k.Uint32;case 64:return e?k.Int64:k.Uint64}return k.Int}case k.Float:switch(r.precision){case ar.HALF:return k.Float16;case ar.SINGLE:return k.Float32;case ar.DOUBLE:return k.Float64}return k.Float;case k.Binary:return k.Binary;case k.LargeBinary:return k.LargeBinary;case k.Utf8:return k.Utf8;case k.LargeUtf8:return k.LargeUtf8;case k.Bool:return k.Bool;case k.Decimal:return k.Decimal;case k.Time:switch(r.unit){case Vt.SECOND:return k.TimeSecond;case Vt.MILLISECOND:return k.TimeMillisecond;case Vt.MICROSECOND:return k.TimeMicrosecond;case Vt.NANOSECOND:return k.TimeNanosecond}return k.Time;case k.Timestamp:switch(r.unit){case Vt.SECOND:return k.TimestampSecond;case Vt.MILLISECOND:return k.TimestampMillisecond;case Vt.MICROSECOND:return k.TimestampMicrosecond;case Vt.NANOSECOND:return k.TimestampNanosecond}return k.Timestamp;case k.Date:switch(r.unit){case nn.DAY:return k.DateDay;case nn.MILLISECOND:return k.DateMillisecond}return k.Date;case k.Interval:switch(r.unit){case zn.DAY_TIME:return k.IntervalDayTime;case zn.YEAR_MONTH:return k.IntervalYearMonth}return k.Interval;case k.Duration:switch(r.unit){case Vt.SECOND:return k.DurationSecond;case Vt.MILLISECOND:return k.DurationMillisecond;case Vt.MICROSECOND:return k.DurationMicrosecond;case Vt.NANOSECOND:return k.DurationNanosecond}return k.Duration;case k.Map:return k.Map;case k.List:return k.List;case k.Struct:return k.Struct;case k.Union:switch(r.mode){case lr.Dense:return k.DenseUnion;case lr.Sparse:return k.SparseUnion}return k.Union;case k.FixedSizeBinary:return k.FixedSizeBinary;case k.FixedSizeList:return k.FixedSizeList;case k.Dictionary:return k.Dictionary}throw new Error(`Unrecognized type '${k[r.typeId]}'`)}se.prototype.visitInt8=null;se.prototype.visitInt16=null;se.prototype.visitInt32=null;se.prototype.visitInt64=null;se.prototype.visitUint8=null;se.prototype.visitUint16=null;se.prototype.visitUint32=null;se.prototype.visitUint64=null;se.prototype.visitFloat16=null;se.prototype.visitFloat32=null;se.prototype.visitFloat64=null;se.prototype.visitDateDay=null;se.prototype.visitDateMillisecond=null;se.prototype.visitTimestampSecond=null;se.prototype.visitTimestampMillisecond=null;se.prototype.visitTimestampMicrosecond=null;se.prototype.visitTimestampNanosecond=null;se.prototype.visitTimeSecond=null;se.prototype.visitTimeMillisecond=null;se.prototype.visitTimeMicrosecond=null;se.prototype.visitTimeNanosecond=null;se.prototype.visitDenseUnion=null;se.prototype.visitSparseUnion=null;se.prototype.visitIntervalDayTime=null;se.prototype.visitIntervalYearMonth=null;se.prototype.visitDuration=null;se.prototype.visitDurationSecond=null;se.prototype.visitDurationMillisecond=null;se.prototype.visitDurationMicrosecond=null;se.prototype.visitDurationNanosecond=null;const pw=new Float64Array(1),Ws=new Uint32Array(pw.buffer);function mw(r){const t=(r&31744)>>10,e=(r&1023)/1024,n=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return n*(e?Number.NaN:1/0);case 0:return n*(e?6103515625e-14*e:0)}return n*Math.pow(2,t-15)*(1+e)}function hF(r){if(r!==r)return 32256;pw[0]=r;const t=(Ws[1]&2147483648)>>16&65535;let e=Ws[1]&2146435072,n=0;return e>=1089470464?Ws[0]>0?e=31744:(e=(e&2080374784)>>16,n=(Ws[1]&1048575)>>10):e<=1056964608?(n=1048576+(Ws[1]&1048575),n=1048576+(n<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,n=(Ws[1]&1048575)+512>>10),t|e|n&65535}let jt=class extends se{};function Yt(r){return(t,e,n)=>{if(t.setValid(e,n!=null))return r(t,e,n)}}const dF=(r,t,e)=>{r[t]=Math.floor(e/864e5)},gw=(r,t,e,n)=>{if(e+1{const i=r+e;n?t[i>>3]|=1<>3]&=~(1<{r[t]=e},Jf=({values:r},t,e)=>{r[t]=e},yw=({values:r},t,e)=>{r[t]=hF(e)},pF=(r,t,e)=>{switch(r.type.precision){case ar.HALF:return yw(r,t,e);case ar.SINGLE:case ar.DOUBLE:return Jf(r,t,e)}},vw=({values:r},t,e)=>{dF(r,t,e.valueOf())},_w=({values:r},t,e)=>{r[t]=BigInt(e)},mF=({stride:r,values:t},e,n)=>{t.set(n.subarray(0,r),r*e)},bw=({values:r,valueOffsets:t},e,n)=>gw(r,t,e,n),ww=({values:r,valueOffsets:t},e,n)=>gw(r,t,e,Qf(n)),gF=(r,t,e)=>{r.type.unit===nn.DAY?vw(r,t,e):_w(r,t,e)},xw=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},Sw=({values:r},t,e)=>{r[t]=BigInt(e)},Tw=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},Iw=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},yF=(r,t,e)=>{switch(r.type.unit){case Vt.SECOND:return xw(r,t,e);case Vt.MILLISECOND:return Sw(r,t,e);case Vt.MICROSECOND:return Tw(r,t,e);case Vt.NANOSECOND:return Iw(r,t,e)}},Ew=({values:r},t,e)=>{r[t]=e},Aw=({values:r},t,e)=>{r[t]=e},Mw=({values:r},t,e)=>{r[t]=e},Cw=({values:r},t,e)=>{r[t]=e},vF=(r,t,e)=>{switch(r.type.unit){case Vt.SECOND:return Ew(r,t,e);case Vt.MILLISECOND:return Aw(r,t,e);case Vt.MICROSECOND:return Mw(r,t,e);case Vt.NANOSECOND:return Cw(r,t,e)}},_F=({values:r,stride:t},e,n)=>{r.set(n.subarray(0,t),t*e)},bF=(r,t,e)=>{const n=r.children[0],i=r.valueOffsets,s=sn.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=i[t],l=i[t+1];a{const n=r.children[0],{valueOffsets:i}=r,s=sn.getVisitFn(n);let{[t]:o,[t+1]:a}=i;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(n,o,u),++o>=a)break},xF=(r,t)=>(e,n,i,s)=>n&&e(n,r,t[s]),SF=(r,t)=>(e,n,i,s)=>n&&e(n,r,t.get(s)),TF=(r,t)=>(e,n,i,s)=>n&&e(n,r,t.get(i.name)),IF=(r,t)=>(e,n,i,s)=>n&&e(n,r,t[i.name]),EF=(r,t,e)=>{const n=r.type.children.map(s=>sn.getVisitFn(s.type)),i=e instanceof Map?TF(t,e):e instanceof Ne?SF(t,e):Array.isArray(e)?xF(t,e):IF(t,e);r.type.children.forEach((s,o)=>i(n[o],r.children[o],s,o))},AF=(r,t,e)=>{r.type.mode===lr.Dense?Ow(r,t,e):Pw(r,t,e)},Ow=(r,t,e)=>{const n=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[n];sn.visit(i,r.valueOffsets[t],e)},Pw=(r,t,e)=>{const n=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[n];sn.visit(i,t,e)},MF=(r,t,e)=>{var n;(n=r.dictionary)===null||n===void 0||n.set(r.values[t],e)},CF=(r,t,e)=>{r.type.unit===zn.DAY_TIME?Rw(r,t,e):Fw(r,t,e)},Rw=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},Fw=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},Dw=({values:r},t,e)=>{r[t]=e},Lw=({values:r},t,e)=>{r[t]=e},Nw=({values:r},t,e)=>{r[t]=e},Bw=({values:r},t,e)=>{r[t]=e},OF=(r,t,e)=>{switch(r.type.unit){case Vt.SECOND:return Dw(r,t,e);case Vt.MILLISECOND:return Lw(r,t,e);case Vt.MICROSECOND:return Nw(r,t,e);case Vt.NANOSECOND:return Bw(r,t,e)}},PF=(r,t,e)=>{const{stride:n}=r,i=r.children[0],s=sn.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=t*n;++o`${Ba(t)}: ${Ba(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new RF(this[un],this[bo])}},RF=class{constructor(t,e){this.childIndex=0,this.children=t.children,this.rowIndex=e,this.childFields=t.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const t=this.childIndex;return te.name)}has(t,e){return t[un].type.children.findIndex(n=>n.name===e)!==-1}getOwnPropertyDescriptor(t,e){if(t[un].type.children.findIndex(n=>n.name===e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const n=t[un].type.children.findIndex(i=>i.name===e);if(n!==-1){const i=xr.visit(t[un].children[n],t[bo]);return Reflect.set(t,e,i),i}}set(t,e,n){const i=t[un].type.children.findIndex(s=>s.name===e);return i!==-1?(sn.visit(t[un].children[i],t[bo],n),Reflect.set(t,e,n)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,n):!1}},Ft=class extends se{};function $t(r){return(t,e)=>t.getValid(e)?r(t,e):null}const DF=(r,t)=>864e5*r[t],LF=(r,t)=>null,Uw=(r,t,e)=>{if(e+1>=t.length)return null;const n=Te(t[e]),i=Te(t[e+1]);return r.subarray(n,i)},NF=({offset:r,values:t},e)=>{const n=r+e;return(t[n>>3]&1<DF(r,t),zw=({values:r},t)=>Te(r[t]),zi=({stride:r,values:t},e)=>t[r*e],BF=({stride:r,values:t},e)=>mw(t[r*e]),Vw=({values:r},t)=>r[t],UF=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),jw=({values:r,valueOffsets:t},e)=>Uw(r,t,e),$w=({values:r,valueOffsets:t},e)=>{const n=Uw(r,t,e);return n!==null?Wd(n):null},kF=({values:r},t)=>r[t],zF=({type:r,values:t},e)=>r.precision!==ar.HALF?t[e]:mw(t[e]),VF=(r,t)=>r.type.unit===nn.DAY?kw(r,t):zw(r,t),Gw=({values:r},t)=>1e3*Te(r[t]),Ww=({values:r},t)=>Te(r[t]),Hw=({values:r},t)=>$b(r[t],BigInt(1e3)),Xw=({values:r},t)=>$b(r[t],BigInt(1e6)),jF=(r,t)=>{switch(r.type.unit){case Vt.SECOND:return Gw(r,t);case Vt.MILLISECOND:return Ww(r,t);case Vt.MICROSECOND:return Hw(r,t);case Vt.NANOSECOND:return Xw(r,t)}},Yw=({values:r},t)=>r[t],qw=({values:r},t)=>r[t],Qw=({values:r},t)=>r[t],Zw=({values:r},t)=>r[t],$F=(r,t)=>{switch(r.type.unit){case Vt.SECOND:return Yw(r,t);case Vt.MILLISECOND:return qw(r,t);case Vt.MICROSECOND:return Qw(r,t);case Vt.NANOSECOND:return Zw(r,t)}},GF=({values:r,stride:t},e)=>lF.decimal(r.subarray(t*e,t*(e+1))),WF=(r,t)=>{const{valueOffsets:e,stride:n,children:i}=r,{[t*n]:s,[t*n+1]:o}=e,l=i[0].slice(s,o-s);return new Ne([l])},HF=(r,t)=>{const{valueOffsets:e,children:n}=r,{[t]:i,[t+1]:s}=e,o=n[0];return new ep(o.slice(i,s-i))},XF=(r,t)=>new tp(r,t),YF=(r,t)=>r.type.mode===lr.Dense?Kw(r,t):Jw(r,t),Kw=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[e];return xr.visit(n,r.valueOffsets[t])},Jw=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[e];return xr.visit(n,t)},qF=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},QF=(r,t)=>r.type.unit===zn.DAY_TIME?tx(r,t):ex(r,t),tx=({values:r},t)=>r.subarray(2*t,2*(t+1)),ex=({values:r},t)=>{const e=r[t],n=new Int32Array(2);return n[0]=Math.trunc(e/12),n[1]=Math.trunc(e%12),n},rx=({values:r},t)=>r[t],nx=({values:r},t)=>r[t],ix=({values:r},t)=>r[t],sx=({values:r},t)=>r[t],ZF=(r,t)=>{switch(r.type.unit){case Vt.SECOND:return rx(r,t);case Vt.MILLISECOND:return nx(r,t);case Vt.MICROSECOND:return ix(r,t);case Vt.NANOSECOND:return sx(r,t)}},KF=(r,t)=>{const{stride:e,children:n}=r,s=n[0].slice(t*e,e);return new Ne([s])};Ft.prototype.visitNull=$t(LF);Ft.prototype.visitBool=$t(NF);Ft.prototype.visitInt=$t(kF);Ft.prototype.visitInt8=$t(zi);Ft.prototype.visitInt16=$t(zi);Ft.prototype.visitInt32=$t(zi);Ft.prototype.visitInt64=$t(Vw);Ft.prototype.visitUint8=$t(zi);Ft.prototype.visitUint16=$t(zi);Ft.prototype.visitUint32=$t(zi);Ft.prototype.visitUint64=$t(Vw);Ft.prototype.visitFloat=$t(zF);Ft.prototype.visitFloat16=$t(BF);Ft.prototype.visitFloat32=$t(zi);Ft.prototype.visitFloat64=$t(zi);Ft.prototype.visitUtf8=$t($w);Ft.prototype.visitLargeUtf8=$t($w);Ft.prototype.visitBinary=$t(jw);Ft.prototype.visitLargeBinary=$t(jw);Ft.prototype.visitFixedSizeBinary=$t(UF);Ft.prototype.visitDate=$t(VF);Ft.prototype.visitDateDay=$t(kw);Ft.prototype.visitDateMillisecond=$t(zw);Ft.prototype.visitTimestamp=$t(jF);Ft.prototype.visitTimestampSecond=$t(Gw);Ft.prototype.visitTimestampMillisecond=$t(Ww);Ft.prototype.visitTimestampMicrosecond=$t(Hw);Ft.prototype.visitTimestampNanosecond=$t(Xw);Ft.prototype.visitTime=$t($F);Ft.prototype.visitTimeSecond=$t(Yw);Ft.prototype.visitTimeMillisecond=$t(qw);Ft.prototype.visitTimeMicrosecond=$t(Qw);Ft.prototype.visitTimeNanosecond=$t(Zw);Ft.prototype.visitDecimal=$t(GF);Ft.prototype.visitList=$t(WF);Ft.prototype.visitStruct=$t(XF);Ft.prototype.visitUnion=$t(YF);Ft.prototype.visitDenseUnion=$t(Kw);Ft.prototype.visitSparseUnion=$t(Jw);Ft.prototype.visitDictionary=$t(qF);Ft.prototype.visitInterval=$t(QF);Ft.prototype.visitIntervalDayTime=$t(tx);Ft.prototype.visitIntervalYearMonth=$t(ex);Ft.prototype.visitDuration=$t(ZF);Ft.prototype.visitDurationSecond=$t(rx);Ft.prototype.visitDurationMillisecond=$t(nx);Ft.prototype.visitDurationMicrosecond=$t(ix);Ft.prototype.visitDurationNanosecond=$t(sx);Ft.prototype.visitFixedSizeList=$t(KF);Ft.prototype.visitMap=$t(HF);const xr=new Ft,so=Symbol.for("keys"),wo=Symbol.for("vals"),oo=Symbol.for("kKeysAsStrings"),Kd=Symbol.for("_kKeysAsStrings");let ep=class{constructor(t){return this[so]=new Ne([t.children[0]]).memoize(),this[wo]=t.children[1],new Proxy(this,new t2)}get[oo](){return this[Kd]||(this[Kd]=Array.from(this[so].toArray(),String))}[Symbol.iterator](){return new JF(this[so],this[wo])}get size(){return this[so].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[so],e=this[wo],n={};for(let i=-1,s=t.length;++i`${Ba(t)}: ${Ba(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}},JF=class{constructor(t,e){this.keys=t,this.vals=e,this.keyIndex=0,this.numKeys=t.length}[Symbol.iterator](){return this}next(){const t=this.keyIndex;return t===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(t),xr.visit(this.vals,t)]})}},t2=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[oo]}has(t,e){return t[oo].includes(e)}getOwnPropertyDescriptor(t,e){if(t[oo].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const n=t[oo].indexOf(e);if(n!==-1){const i=xr.visit(Reflect.get(t,wo),n);return Reflect.set(t,e,i),i}}set(t,e,n){const i=t[oo].indexOf(e);return i!==-1?(sn.visit(Reflect.get(t,wo),i,n),Reflect.set(t,e,n)):Reflect.has(t,e)?Reflect.set(t,e,n):!1}};Object.defineProperties(ep.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[so]:{writable:!0,enumerable:!1,configurable:!1,value:null},[wo]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Kd]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let uy;function ox(r,t,e,n){const{length:i=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?i:e;return s<0&&(s=(s%i+i)%i),o<0&&(o=(o%i+i)%i),oi&&(o=i),n?n(r,s,o):[s,o]}const rp=(r,t)=>r<0?t+r:r,cy=r=>r!==r;function ko(r){if(typeof r!=="object"||r===null)return cy(r)?cy:e=>e===r;if(r instanceof Date){const e=r.valueOf();return n=>n instanceof Date?n.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?ZR(r,e):!1:r instanceof Map?r2(r):Array.isArray(r)?e2(r):r instanceof Ne?n2(r):i2(r,!0)}function e2(r){const t=[];for(let e=-1,n=r.length;++e!1;const n=[];for(let i=-1,s=e.length;++i{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return s2(r,e);case Map:return hy(r,e,e.keys());case ep:case tp:case Object:case void 0:return hy(r,e,t||Object.keys(e))}return e instanceof Ne?o2(r,e):!1}}function s2(r,t){const e=r.length;if(t.length!==e)return!1;for(let n=-1;++n>n}function Ru(r,t,e){const n=e.byteLength+7&-8;if(r>0||e.byteLength>3):Fu(new np(e,r,t,null,ax)).subarray(0,n)),i}return e}function Fu(r){const t=[];let e=0,n=0,i=0;for(const o of r)o&&(i|=1<0)&&(t[e++]=i);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}let np=class{constructor(t,e,n,i,s){this.bytes=t,this.length=n,this.context=i,this.get=s,this.bit=e%8,this.byteIndex=e>>3,this.byte=t[this.byteIndex++],this.index=0}next(){return this.index>3<<3,i=t+(t%8===0?0:8-t%8);return Jd(r,t,i)+Jd(r,n,e)+l2(r,i>>3,n-i>>3)}function l2(r,t,e){let n=0,i=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:i+e;for(;o-i>=4;)n+=Oh(s.getUint32(i)),i+=4;for(;o-i>=2;)n+=Oh(s.getUint16(i)),i+=2;for(;o-i>=1;)n+=Oh(s.getUint8(i)),i+=1;return n}function Oh(r){let t=Math.trunc(r);return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}const u2=-1;let Ae=class tf{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:t}=this;return Ot.isSparseUnion(t)?this.children.some(e=>e.nullable):Ot.isDenseUnion(t)?this.children.some(e=>e.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let t=0;const{valueOffsets:e,values:n,nullBitmap:i,typeIds:s}=this;return e&&(t+=e.byteLength),n&&(t+=n.byteLength),i&&(t+=i.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(Ot.isUnion(this.type))return this.children.reduce((n,i)=>n+i.nullCount,0);let t=this._nullCount,e;return t<=u2&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-Jd(e,this.offset,this.offset+this.length)),t}constructor(t,e,n,i,s,o=[],a){this.type=t,this.children=o,this.dictionary=a,this.offset=Math.floor(Math.max(e||0,0)),this.length=Math.floor(Math.max(n||0,0)),this._nullCount=Math.floor(Math.max(i||0,-1));let l;s instanceof tf?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=ii(t),s&&((l=s[0])&&(this.valueOffsets=l),(l=s[1])&&(this.values=l),(l=s[2])&&(this.nullBitmap=l),(l=s[3])&&(this.typeIds=l)))}getValid(t){const{type:e}=this;if(Ot.isUnion(e)){const n=e,i=this.children[n.typeIdToChildIndex[this.typeIds[t]]],s=n.mode===lr.Dense?this.valueOffsets[t]:t;return i.getValid(s)}if(this.nullable&&this.nullCount>0){const n=this.offset+t;return(this.nullBitmap[n>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(Ru(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];n=(h&u)!==0,s[c]=e?h|u:h&~u}return n!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,n=this.length,i=this._nullCount,s=this,o=this.children){return new tf(t,e,n,i,s,o,this.dictionary)}slice(t,e){const{stride:n,typeId:i,children:s}=this,o=+(this._nullCount===0)-1,a=i===16?n:1,l=this._sliceBuffers(t,e,n,i);return this.clone(this.type,this.offset+t,e,o,l,s.length===0||this.valueOffsets?s:this._sliceChildren(s,a*t,a*e))}_changeLengthAndBackfillNullBitmap(t){if(this.typeId===k.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:n}=this,i=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);i[e>>3]=(1<0&&i.set(Ru(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[ni.VALIDITY]=i,this.clone(this.type,0,t,n+(t-e),s)}_sliceBuffers(t,e,n,i){let s;const{buffers:o}=this;return(s=o[ni.TYPE])&&(o[ni.TYPE]=s.subarray(t,t+e)),(s=o[ni.OFFSET])&&(o[ni.OFFSET]=s.subarray(t,t+e+1))||(s=o[ni.DATA])&&(o[ni.DATA]=i===6?s:s.subarray(n*t,n*(t+e))),o}_sliceChildren(t,e,n){return t.map(i=>i.slice(e,n))}};Ae.prototype.children=Object.freeze([]);class Sa extends se{visit(t){return this.getVisitFn(t.type).call(this,t)}visitNull(t){const{["type"]:e,["offset"]:n=0,["length"]:i=0}=t;return new Ae(e,n,i,i)}visitBool(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length>>3,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitInt(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitFloat(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitUtf8(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.data),s=ce(t.nullBitmap),o=ia(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[o,i,s])}visitLargeUtf8(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.data),s=ce(t.nullBitmap),o=Kg(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[o,i,s])}visitBinary(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.data),s=ce(t.nullBitmap),o=ia(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[o,i,s])}visitLargeBinary(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.data),s=ce(t.nullBitmap),o=Kg(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[o,i,s])}visitFixedSizeBinary(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitDate(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitTimestamp(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitTime(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitDecimal(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitList(t){const{["type"]:e,["offset"]:n=0,["child"]:i}=t,s=ce(t.nullBitmap),o=ia(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[o,void 0,s],[i])}visitStruct(t){const{["type"]:e,["offset"]:n=0,["children"]:i=[]}=t,s=ce(t.nullBitmap),{length:o=i.reduce((l,{length:u})=>Math.max(l,u),0),nullCount:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,void 0,s],i)}visitUnion(t){const{["type"]:e,["offset"]:n=0,["children"]:i=[]}=t,s=xe(e.ArrayType,t.typeIds),{["length"]:o=s.length,["nullCount"]:a=-1}=t;if(Ot.isSparseUnion(e))return new Ae(e,n,o,a,[void 0,void 0,void 0,s],i);const l=ia(t.valueOffsets);return new Ae(e,n,o,a,[l,void 0,void 0,s],i)}visitDictionary(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.indices.ArrayType,t.data),{["dictionary"]:o=new Ne([new Sa().visit({type:e.dictionary})])}=t,{["length"]:a=s.length,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[void 0,s,i],[],o)}visitInterval(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitDuration(t){const{["type"]:e,["offset"]:n=0}=t,i=ce(t.nullBitmap),s=xe(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,s,i])}visitFixedSizeList(t){const{["type"]:e,["offset"]:n=0,["child"]:i=new Sa().visit({type:e.valueType})}=t,s=ce(t.nullBitmap),{["length"]:o=i.length/ii(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Ae(e,n,o,a,[void 0,void 0,s],[i])}visitMap(t){const{["type"]:e,["offset"]:n=0,["child"]:i=new Sa().visit({type:e.childType})}=t,s=ce(t.nullBitmap),o=ia(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Ae(e,n,a,l,[o,void 0,s],[i])}}const c2=new Sa;function le(r){return c2.visit(r)}let dy=class{constructor(t=0,e){this.numChunks=t,this.getChunkIterator=e,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndext.nullable)}function lx(r){return r.reduce((t,e)=>t+e.nullCount,0)}function ux(r){return r.reduce((t,e,n)=>(t[n+1]=t[n]+e.length,t),new Uint32Array(r.length+1))}function cx(r,t,e,n){const i=[];for(let s=-1,o=r.length;++s=n)break;if(e>=l+u)continue;if(l>=e&&l+u<=n){i.push(a);continue}const c=Math.max(0,e-l),h=Math.min(n-l,u);i.push(a.slice(c,h-c))}return i.length===0&&i.push(r[0].slice(0,0)),i}function ip(r,t,e,n){let i=0,s=0,o=t.length-1;do{if(i>=o-1)return e0?0:-1}function f2(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let n=0;for(const i of new np(e,r.offset+(t||0),r.length,e,ax)){if(!i)return n;++n}return-1}function Zt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case k.Union:break;case k.Dictionary:break;default:return f2(r,e)}const n=xr.getVisitFn(r),i=ko(t);for(let s=(e||0)-1,o=r.length;++s{const i=r.data[n];return i.values.subarray(0,i.length)[Symbol.iterator]()});let e=0;return new dy(r.data.length,n=>{const s=r.data[n].length,o=r.slice(e,e+s);return e+=s,new p2(o)})}let p2=class{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof Ae)))throw new TypeError("Vector constructor expects an Array of Data instances.");const o=(e=s[0])===null||e===void 0?void 0:e.type;switch(s.length){case 0:this._offsets=[0];break;case 1:{const{get:a,set:l,indexOf:u}=mx[o.typeId],c=s[0];this.isValid=h=>sp(c,h),this.get=h=>a(c,h),this.set=(h,f)=>l(c,h,f),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,gx[o.typeId]),this._offsets=ux(s);break}this.data=s,this.type=o,this.stride=ii(o),this.numChildren=(i=(n=o.children)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return h2(this.data)}get nullCount(){return lx(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${k[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(rp(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return op.visit(this)}concat(...t){return new ls(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new ls(ox(this,t,e,({data:n,_offsets:i},s,o)=>cx(n,i,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:n,stride:i,ArrayType:s}=this;switch(t.typeId){case k.Int:case k.Float:case k.Decimal:case k.Time:case k.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,n*i);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*i),o.offset),o.offset+=l*i,o),{array:new s(n*i),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(t){var e;return this.getChildAt((e=this.type.children)===null||e===void 0?void 0:e.findIndex(n=>n.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return Ot.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(Ot.isDictionary(this.type)){const t=new fy(this.data[0].dictionary),e=this.data.map(n=>{const i=n.clone();return i.dictionary=t,i});return new ls(e)}return new fy(this)}unmemoize(){if(Ot.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(n=>{const i=n.clone();return i.dictionary=t,i});return new ls(e)}return this}};px=Symbol.toStringTag;Ne[px]=(r=>{r.type=Ot.prototype,r.data=[],r.length=0,r.stride=1,r.numChildren=0,r._offsets=new Uint32Array([0]),r[Symbol.isConcatSpreadable]=!0;const t=Object.keys(k).map(e=>k[e]).filter(e=>typeof e=="number"&&e!==k.NONE);for(const e of t){const n=xr.getVisitFnByTypeId(e),i=sn.getVisitFnByTypeId(e),s=Lu.getVisitFnByTypeId(e);mx[e]={get:n,set:i,indexOf:s},gx[e]=Object.create(r,{isValid:{value:Du(sp)},get:{value:Du(xr.getVisitFnByTypeId(e))},set:{value:hx(sn.getVisitFnByTypeId(e))},indexOf:{value:dx(Lu.getVisitFnByTypeId(e))}})}return"Vector"})(Ne.prototype);let fy=class yx extends Ne{constructor(t){super(t.data);const e=this.get,n=this.set,i=this.slice,s=new Array(this.length);Object.defineProperty(this,"get",{value(o){const a=s[o];if(a!==void 0)return a;const l=e.call(this,o);return s[o]=l,l}}),Object.defineProperty(this,"set",{value(o,a){n.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new yx(i.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Ne(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}};class ef{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}offset(){return this.bb.readInt64(this.bb_pos)}metaDataLength(){return this.bb.readInt32(this.bb_pos+8)}bodyLength(){return this.bb.readInt64(this.bb_pos+16)}static sizeOf(){return 24}static createBlock(t,e,n,i){return t.prep(8,24),t.writeInt64(BigInt(i??0)),t.pad(4),t.writeInt32(n),t.writeInt64(BigInt(e??0)),t.offset()}}class Er{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsFooter(t,e){return(e||new Er).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFooter(t,e){return t.setPosition(t.position()+_e),(e||new Er).__init(t.readInt32(t.position())+t.position(),t)}version(){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):je.V1}schema(t){const e=this.bb.__offset(this.bb_pos,6);return e?(t||new In).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dictionaries(t,e){const n=this.bb.__offset(this.bb_pos,8);return n?(e||new ef).__init(this.bb.__vector(this.bb_pos+n)+t*24,this.bb):null}dictionariesLength(){const t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}recordBatches(t,e){const n=this.bb.__offset(this.bb_pos,10);return n?(e||new ef).__init(this.bb.__vector(this.bb_pos+n)+t*24,this.bb):null}recordBatchesLength(){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.__vector_len(this.bb_pos+t):0}customMetadata(t,e){const n=this.bb.__offset(this.bb_pos,12);return n?(e||new qe).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}customMetadataLength(){const t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startFooter(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,je.V1)}static addSchema(t,e){t.addFieldOffset(1,e,0)}static addDictionaries(t,e){t.addFieldOffset(2,e,0)}static startDictionariesVector(t,e){t.startVector(24,e,8)}static addRecordBatches(t,e){t.addFieldOffset(3,e,0)}static startRecordBatchesVector(t,e){t.startVector(24,e,8)}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endFooter(t){return t.endObject()}static finishFooterBuffer(t,e){t.finish(e)}static finishSizePrefixedFooterBuffer(t,e){t.finish(e,void 0,!0)}}let Le=class us{constructor(t=[],e,n,i=je.V5){this.fields=t||[],this.metadata=e||new Map,n||(n=rf(this.fields)),this.dictionaries=n,this.metadataVersion=i}get[Symbol.toStringTag](){return"Schema"}get names(){return this.fields.map(t=>t.name)}toString(){return`Schema<{ ${this.fields.map((t,e)=>`${e}: ${t}`).join(", ")} }>`}select(t){const e=new Set(t),n=this.fields.filter(i=>e.has(i.name));return new us(n,this.metadata)}selectAt(t){const e=t.map(n=>this.fields[n]).filter(Boolean);return new us(e,this.metadata)}assign(...t){const e=t[0]instanceof us?t[0]:Array.isArray(t[0])?new us(t[0]):new us(t),n=[...this.fields],i=Ll(Ll(new Map,this.metadata),e.metadata),s=e.fields.filter(a=>{const l=n.findIndex(u=>u.name===a.name);return~l?(n[l]=a.clone({metadata:Ll(Ll(new Map,n[l].metadata),a.metadata)}))&&!1:!0}),o=rf(s,new Map);return new us([...n,...s],i,new Map([...this.dictionaries,...o]))}};Le.prototype.fields=null;Le.prototype.metadata=null;Le.prototype.dictionaries=null;class Pe{static new(...t){let[e,n,i,s]=t;return t[0]&&typeof t[0]=="object"&&({name:e}=t[0],n===void 0&&(n=t[0].type),i===void 0&&(i=t[0].nullable),s===void 0&&(s=t[0].metadata)),new Pe(`${e}`,n,i,s)}constructor(t,e,n=!1,i){this.name=t,this.type=e,this.nullable=n,this.metadata=i||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...t){let[e,n,i,s]=t;return!t[0]||typeof t[0]!="object"?[e=this.name,n=this.type,i=this.nullable,s=this.metadata]=t:{name:e=this.name,type:n=this.type,nullable:i=this.nullable,metadata:s=this.metadata}=t[0],Pe.new(e,n,i,s)}}Pe.prototype.type=null;Pe.prototype.name=null;Pe.prototype.nullable=null;Pe.prototype.metadata=null;function Ll(r,t){return new Map([...r||new Map,...t||new Map])}function rf(r,t=new Map){for(let e=-1,n=r.length;++e0&&rf(s.children,t)}return t}var m2=kb,g2=Mo;class Va{static decode(t){t=new g2(ce(t));const e=Er.getRootAsFooter(t),n=Le.decode(e.schema(),new Map,e.version());return new y2(n,e)}static encode(t){const e=new m2,n=Le.encode(e,t.schema);Er.startRecordBatchesVector(e,t.numRecordBatches);for(const o of[...t.recordBatches()].slice().reverse())Fi.encode(e,o);const i=e.endVector();Er.startDictionariesVector(e,t.numDictionaries);for(const o of[...t.dictionaryBatches()].slice().reverse())Fi.encode(e,o);const s=e.endVector();return Er.startFooter(e),Er.addSchema(e,n),Er.addVersion(e,je.V5),Er.addRecordBatches(e,i),Er.addDictionaries(e,s),Er.finishFooterBuffer(e,Er.endFooter(e)),e.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(t,e=je.V5,n,i){this.schema=t,this.version=e,n&&(this._recordBatches=n),i&&(this._dictionaryBatches=i)}*recordBatches(){for(let t,e=-1,n=this.numRecordBatches;++e=0&&t=0&&t=0&&t=0&&tthis._closedPromiseResolve=t)}get closed(){return this._closedPromise}cancel(t){return Jt(this,void 0,void 0,function*(){yield this.return(t)})}write(t){this._ensureOpen()&&(this.resolvers.length<=0?this._values.push(t):this.resolvers.shift().resolve({done:!1,value:t}))}abort(t){this._closedPromiseResolve&&(this.resolvers.length<=0?this._error={error:t}:this.resolvers.shift().reject({done:!0,value:t}))}close(){if(this._closedPromiseResolve){const{resolvers:t}=this;for(;t.length>0;)t.shift().resolve(Be);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(t){return Yr.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,t)}toNodeStream(t){return Yr.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,t)}throw(t){return Jt(this,void 0,void 0,function*(){return yield this.abort(t),Be})}return(t){return Jt(this,void 0,void 0,function*(){return yield this.close(),Be})}read(t){return Jt(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return Jt(this,void 0,void 0,function*(){return(yield this.next(t,"peek")).value})}next(...t){return this._values.length>0?Promise.resolve({done:!1,value:this._values.shift()}):this._error?Promise.reject({done:!0,value:this._error.error}):this._closedPromiseResolve?new Promise((e,n)=>{this.resolvers.push({resolve:e,reject:n})}):Promise.resolve(Be)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class Xl extends v2{write(t){if((t=ce(t)).byteLength>0)return super.write(t)}toString(t=!1){return t?Wd(this.toUint8Array(!0)):this.toUint8Array(!1).then(Wd)}toUint8Array(t=!1){return t?kn(this._values)[0]:Jt(this,void 0,void 0,function*(){var e,n,i,s;const o=[];let a=0;try{for(var l=!0,u=Bn(this),c;c=yield u.next(),e=c.done,!e;l=!0){s=c.value,l=!1;const h=s;o.push(h),a+=h.byteLength}}catch(h){n={error:h}}finally{try{!l&&!e&&(i=u.return)&&(yield i.call(u))}finally{if(n)throw n.error}}return kn(o,a)[0]})}}class Nu{constructor(t){t&&(this.source=new _2(Yr.fromIterable(t)))}[Symbol.iterator](){return this}next(t){return this.source.next(t)}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}peek(t){return this.source.peek(t)}read(t){return this.source.read(t)}}class Po{constructor(t){t instanceof Po?this.source=t.source:t instanceof Xl?this.source=new ts(Yr.fromAsyncIterable(t)):Lb(t)?this.source=new ts(Yr.fromNodeStream(t)):Zf(t)?this.source=new ts(Yr.fromDOMStream(t)):Db(t)?this.source=new ts(Yr.fromDOMStream(t.body)):Qa(t)?this.source=new ts(Yr.fromIterable(t)):Is(t)?this.source=new ts(Yr.fromAsyncIterable(t)):Uo(t)&&(this.source=new ts(Yr.fromAsyncIterable(t)))}[Symbol.asyncIterator](){return this}next(t){return this.source.next(t)}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}get closed(){return this.source.closed}cancel(t){return this.source.cancel(t)}peek(t){return this.source.peek(t)}read(t){return this.source.read(t)}}class _2{constructor(t){this.source=t}cancel(t){this.return(t)}peek(t){return this.next(t,"peek").value}read(t){return this.next(t,"read").value}next(t,e="read"){return this.source.next({cmd:e,size:t})}throw(t){return Object.create(this.source.throw&&this.source.throw(t)||Be)}return(t){return Object.create(this.source.return&&this.source.return(t)||Be)}}class ts{constructor(t){this.source=t,this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}cancel(t){return Jt(this,void 0,void 0,function*(){yield this.return(t)})}get closed(){return this._closedPromise}read(t){return Jt(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return Jt(this,void 0,void 0,function*(){return(yield this.next(t,"peek")).value})}next(t){return Jt(this,arguments,void 0,function*(e,n="read"){return yield this.source.next({cmd:n,size:e})})}throw(t){return Jt(this,void 0,void 0,function*(){const e=this.source.throw&&(yield this.source.throw(t))||Be;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}return(t){return Jt(this,void 0,void 0,function*(){const e=this.source.return&&(yield this.source.return(t))||Be;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}}class my extends Nu{constructor(t,e){super(),this.position=0,this.buffer=ce(t),this.size=e===void 0?this.buffer.byteLength:e}readInt32(t){const{buffer:e,byteOffset:n}=this.readAt(t,4);return new DataView(e,n).getInt32(0,!0)}seek(t){return this.position=Math.min(t,this.size),t>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),n=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let i=e[3]*n[3];this.buffer[0]=i&65535;let s=i>>>16;return i=e[2]*n[3],s+=i,i=e[3]*n[2]>>>0,s+=i,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*n[3]+e[2]*n[2]+e[3]*n[1],this.buffer[1]+=e[0]*n[3]+e[1]*n[2]+e[2]*n[1]+e[3]*n[0]<<16,this}_plus(t){const e=this.buffer[0]+t.buffer[0]>>>0;this.buffer[1]+=t.buffer[1],e>>0&&++this.buffer[1],this.buffer[0]=e}lessThan(t){return this.buffer[1]>>0,e[2]=this.buffer[2]+t.buffer[2]>>>0,e[1]=this.buffer[1]+t.buffer[1]>>>0,e[0]=this.buffer[0]+t.buffer[0]>>>0,e[0]>>0&&++e[1],e[1]>>0&&++e[2],e[2]>>0&&++e[3],this.buffer[3]=e[3],this.buffer[2]=e[2],this.buffer[1]=e[1],this.buffer[0]=e[0],this}hex(){return`${fo(this.buffer[3])} ${fo(this.buffer[2])} ${fo(this.buffer[1])} ${fo(this.buffer[0])}`}static multiply(t,e){return new ti(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new ti(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return ti.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return ti.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const n=t.startsWith("-"),i=t.length,s=new ti(e);for(let o=n?1:0;o0&&this.readData(t,n)||new Uint8Array(0)}readOffsets(t,e){return this.readData(t,e)}readTypeIds(t,e){return this.readData(t,e)}readData(t,{length:e,offset:n}=this.nextBufferRange()){return this.bytes.subarray(n,n+e)}readDictionary(t){return this.dictionaries.get(t.id)}}class x2 extends _x{constructor(t,e,n,i,s){super(new Uint8Array(0),e,n,i,s),this.sources=t}readNullBitmap(t,e,{offset:n}=this.nextBufferRange()){return e<=0?new Uint8Array(0):Fu(this.sources[n])}readOffsets(t,{offset:e}=this.nextBufferRange()){return xe(Uint8Array,xe(t.OffsetArrayType,this.sources[e]))}readTypeIds(t,{offset:e}=this.nextBufferRange()){return xe(Uint8Array,xe(t.ArrayType,this.sources[e]))}readData(t,{offset:e}=this.nextBufferRange()){const{sources:n}=this;return Ot.isTimestamp(t)||(Ot.isInt(t)||Ot.isTime(t))&&t.bitWidth===64||Ot.isDuration(t)||Ot.isDate(t)&&t.unit===nn.MILLISECOND?xe(Uint8Array,Ta.convertArray(n[e])):Ot.isDecimal(t)?xe(Uint8Array,w2.convertArray(n[e])):Ot.isBinary(t)||Ot.isLargeBinary(t)||Ot.isFixedSizeBinary(t)?S2(n[e]):Ot.isBool(t)?Fu(n[e]):Ot.isUtf8(t)||Ot.isLargeUtf8(t)?Qf(n[e].join("")):xe(Uint8Array,xe(t.ArrayType,n[e].map(i=>+i)))}}function S2(r){const t=r.join(""),e=new Uint8Array(t.length/2);for(let n=0;n>1]=Number.parseInt(t.slice(n,n+2),16);return e}let Nt=class extends se{compareSchemas(t,e){return t===e||e instanceof t.constructor&&this.compareManyFields(t.fields,e.fields)}compareManyFields(t,e){return t===e||Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((n,i)=>this.compareFields(n,e[i]))}compareFields(t,e){return t===e||e instanceof t.constructor&&t.name===e.name&&t.nullable===e.nullable&&this.visit(t.type,e.type)}};function mr(r,t){return t instanceof r.constructor}function Fs(r,t){return r===t||mr(r,t)}function di(r,t){return r===t||mr(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function lc(r,t){return r===t||mr(r,t)&&r.precision===t.precision}function T2(r,t){return r===t||mr(r,t)&&r.byteWidth===t.byteWidth}function up(r,t){return r===t||mr(r,t)&&r.unit===t.unit}function Za(r,t){return r===t||mr(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function Ka(r,t){return r===t||mr(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function I2(r,t){return r===t||mr(r,t)&&r.children.length===t.children.length&&Di.compareManyFields(r.children,t.children)}function E2(r,t){return r===t||mr(r,t)&&r.children.length===t.children.length&&Di.compareManyFields(r.children,t.children)}function cp(r,t){return r===t||mr(r,t)&&r.mode===t.mode&&r.typeIds.every((e,n)=>e===t.typeIds[n])&&Di.compareManyFields(r.children,t.children)}function A2(r,t){return r===t||mr(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&Di.visit(r.indices,t.indices)&&Di.visit(r.dictionary,t.dictionary)}function hp(r,t){return r===t||mr(r,t)&&r.unit===t.unit}function Ja(r,t){return r===t||mr(r,t)&&r.unit===t.unit}function M2(r,t){return r===t||mr(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&Di.compareManyFields(r.children,t.children)}function C2(r,t){return r===t||mr(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&Di.compareManyFields(r.children,t.children)}Nt.prototype.visitNull=Fs;Nt.prototype.visitBool=Fs;Nt.prototype.visitInt=di;Nt.prototype.visitInt8=di;Nt.prototype.visitInt16=di;Nt.prototype.visitInt32=di;Nt.prototype.visitInt64=di;Nt.prototype.visitUint8=di;Nt.prototype.visitUint16=di;Nt.prototype.visitUint32=di;Nt.prototype.visitUint64=di;Nt.prototype.visitFloat=lc;Nt.prototype.visitFloat16=lc;Nt.prototype.visitFloat32=lc;Nt.prototype.visitFloat64=lc;Nt.prototype.visitUtf8=Fs;Nt.prototype.visitLargeUtf8=Fs;Nt.prototype.visitBinary=Fs;Nt.prototype.visitLargeBinary=Fs;Nt.prototype.visitFixedSizeBinary=T2;Nt.prototype.visitDate=up;Nt.prototype.visitDateDay=up;Nt.prototype.visitDateMillisecond=up;Nt.prototype.visitTimestamp=Za;Nt.prototype.visitTimestampSecond=Za;Nt.prototype.visitTimestampMillisecond=Za;Nt.prototype.visitTimestampMicrosecond=Za;Nt.prototype.visitTimestampNanosecond=Za;Nt.prototype.visitTime=Ka;Nt.prototype.visitTimeSecond=Ka;Nt.prototype.visitTimeMillisecond=Ka;Nt.prototype.visitTimeMicrosecond=Ka;Nt.prototype.visitTimeNanosecond=Ka;Nt.prototype.visitDecimal=Fs;Nt.prototype.visitList=I2;Nt.prototype.visitStruct=E2;Nt.prototype.visitUnion=cp;Nt.prototype.visitDenseUnion=cp;Nt.prototype.visitSparseUnion=cp;Nt.prototype.visitDictionary=A2;Nt.prototype.visitInterval=hp;Nt.prototype.visitIntervalDayTime=hp;Nt.prototype.visitIntervalYearMonth=hp;Nt.prototype.visitDuration=Ja;Nt.prototype.visitDurationSecond=Ja;Nt.prototype.visitDurationMillisecond=Ja;Nt.prototype.visitDurationMicrosecond=Ja;Nt.prototype.visitDurationNanosecond=Ja;Nt.prototype.visitFixedSizeList=M2;Nt.prototype.visitMap=C2;const Di=new Nt;function nf(r,t){return Di.compareSchemas(r,t)}function Ph(r,t){return O2(r,t.map(e=>e.data.concat()))}function O2(r,t){const e=[...r.fields],n=[],i={numBatches:t.reduce((h,f)=>Math.max(h,f.length),0)};let s=0,o=0,a=-1;const l=t.length;let u,c=[];for(;i.numBatches-- >0;){for(o=Number.POSITIVE_INFINITY,a=-1;++a0&&(n[s++]=le({type:new dr(e),length:o,nullCount:0,children:c.slice()})))}return[r=r.assign(e),n.map(h=>new _r(r,h))]}function P2(r,t,e,n,i){var s;const o=(t+63&-64)>>3;for(let a=-1,l=n.length;++a=t)c===t?e[a]=u:(e[a]=u.slice(0,t),i.numBatches=Math.max(i.numBatches,n[a].unshift(u.slice(t,c-t))));else{const h=r[a];r[a]=h.clone({nullable:!0}),e[a]=(s=u==null?void 0:u._changeLengthAndBackfillNullBitmap(t))!==null&&s!==void 0?s:le({type:h.type,length:t,nullCount:t,nullBitmap:new Uint8Array(o)})}}return e}var bx;let Li=class cs{constructor(...t){var e,n;if(t.length===0)return this.batches=[],this.schema=new Le([]),this._offsets=[0],this;let i,s;t[0]instanceof Le&&(i=t.shift()),t.at(-1)instanceof Uint32Array&&(s=t.pop());const o=l=>{if(l){if(l instanceof _r)return[l];if(l instanceof cs)return l.batches;if(l instanceof Ae){if(l.type instanceof dr)return[new _r(new Le(l.type.children),l)]}else{if(Array.isArray(l))return l.flatMap(u=>o(u));if(typeof l[Symbol.iterator]=="function")return[...l].flatMap(u=>o(u));if(typeof l=="object"){const u=Object.keys(l),c=u.map(d=>new Ne([l[d]])),h=i??new Le(u.map((d,m)=>new Pe(String(d),c[m].type,c[m].nullable))),[,f]=Ph(h,c);return f.length===0?[new _r(l)]:f}}}return[]},a=t.flatMap(l=>o(l));if(i=(n=i??((e=a[0])===null||e===void 0?void 0:e.schema))!==null&&n!==void 0?n:new Le([]),!(i instanceof Le))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const l of a){if(!(l instanceof _r))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!nf(i,l.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=i,this.batches=a,this._offsets=s??ux(this.data)}get data(){return this.batches.map(({data:t})=>t)}get numCols(){return this.schema.fields.length}get numRows(){return this.data.reduce((t,e)=>t+e.length,0)}get nullCount(){return this._nullCount===-1&&(this._nullCount=lx(this.data)),this._nullCount}isValid(t){return!1}get(t){return null}at(t){return this.get(rp(t,this.numRows))}set(t,e){}indexOf(t,e){return-1}[Symbol.iterator](){return this.batches.length>0?op.visit(new Ne(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ ${this.toArray().join(`, `)} -]`}concat(...t){const e=this.schema,n=this.data.concat(t.flatMap(({data:i})=>i));return new cs(e,n.map(i=>new _r(e,i)))}slice(t,e){const n=this.schema;[t,e]=ox({length:this.numRows},t,e);const i=cx(this.data,this._offsets,t,e);return new cs(n,i.map(s=>new _r(n,s)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&tn.children[t]);if(e.length===0){const{type:n}=this.schema.fields[t],i=le({type:n,length:0,nullCount:0});e.push(i._changeLengthAndBackfillNullBitmap(this.numRows))}return new Ne(e)}return null}setChild(t,e){var n;return this.setChildAt((n=this.schema.fields)===null||n===void 0?void 0:n.findIndex(i=>i.name===t),e)}setChildAt(t,e){let n=this.schema,i=[...this.batches];if(t>-1&&tthis.getChildAt(u));[s[t],a[t]]=[o,e],[n,i]=Ph(n,a)}return new cs(n,i)}select(t){const e=this.schema.fields.reduce((n,i,s)=>n.set(i.name,s),new Map);return this.selectAt(t.map(n=>e.get(n)).filter(n=>n>-1))}selectAt(t){const e=this.schema.selectAt(t),n=this.batches.map(i=>i.selectAt(t));return new cs(e,n)}assign(t){const e=this.schema.fields,[n,i]=t.schema.fields.reduce((a,l,u)=>{const[c,h]=a,f=e.findIndex(d=>d.name===l.name);return~f?h[f]=u:c.push(u),a},[[],[]]),s=this.schema.assign(t.schema),o=[...e.map((a,l)=>[l,i[l]]).map(([a,l])=>l===void 0?this.getChildAt(a):t.getChildAt(l)),...n.map(a=>t.getChildAt(a))].filter(Boolean);return new cs(...Ph(s,o))}};bx=Symbol.toStringTag;Li[bx]=(r=>(r.schema=null,r.batches=[],r._offsets=new Uint32Array([0]),r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,r.isValid=Du(sp),r.get=Du(xr.getVisitFn(k.Struct)),r.set=hx(sn.getVisitFn(k.Struct)),r.indexOf=dx(Lu.getVisitFn(k.Struct)),"Table"))(Li.prototype);var wx;let _r=class ba{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof Le))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=le({nullCount:0,type:new dr(this.schema.fields),children:this.schema.fields.map(e=>le({type:e.type,nullCount:0}))})]=t,!(this.data instanceof Ae))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=gy(this.schema,this.data.children);break}case 1:{const[e]=t,{fields:n,children:i,length:s}=Object.keys(e).reduce((l,u,c)=>(l.children[c]=e[u],l.length=Math.max(l.length,e[u].length),l.fields[c]=Pe.new({name:u,type:e[u].type,nullable:!0}),l),{length:0,fields:new Array,children:new Array}),o=new Le(n),a=le({type:new dr(n),length:s,children:i,nullCount:0});[this.schema,this.data]=gy(o,a.children,s);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=xx(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(t){return this.data.getValid(t)}get(t){return xr.visit(this.data,t)}at(t){return this.get(rp(t,this.numRows))}set(t,e){return sn.visit(this.data,t,e)}indexOf(t,e){return Lu.visit(this.data,t,e)}[Symbol.iterator](){return op.visit(new Ne([this.data]))}toArray(){return[...this]}concat(...t){return new Li(this.schema,[this,...t])}slice(t,e){const[n]=new Ne([this.data]).slice(t,e).data;return new ba(this.schema,n)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(n=>n.name===t))}getChildAt(t){return t>-1&&ti.name===t),e)}setChildAt(t,e){let n=this.schema,i=this.data;if(t>-1&&ta.name===s);~o&&(i[o]=this.data.children[o])}return new ba(e,le({type:n,length:this.numRows,children:i}))}selectAt(t){const e=this.schema.selectAt(t),n=t.map(s=>this.data.children[s]).filter(Boolean),i=le({type:new dr(e.fields),length:this.numRows,children:n});return new ba(e,i)}};wx=Symbol.toStringTag;_r[wx]=(r=>(r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(_r.prototype);function gy(r,t,e=t.reduce((n,i)=>Math.max(n,i.length),0)){var n;const i=[...r.fields],s=[...t],o=(e+63&-64)>>3;for(const[a,l]of r.fields.entries()){const u=t[a];(!u||u.length!==e)&&(i[a]=l.clone({nullable:!0}),s[a]=(n=u==null?void 0:u._changeLengthAndBackfillNullBitmap(e))!==null&&n!==void 0?n:le({type:l.type,length:e,nullCount:e,nullBitmap:new Uint8Array(o)}))}return[r.assign(i),le({type:new dr(i),length:e,children:s})]}function xx(r,t,e=new Map){var n,i;if(((n=r==null?void 0:r.length)!==null&&n!==void 0?n:0)>0&&(r==null?void 0:r.length)===(t==null?void 0:t.length))for(let s=-1,o=r.length;++sle({type:i.type})),n=le({type:new dr(t.fields),nullCount:0,children:e});super(t,n)}}let bi=class Sn{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMessage(t,e){return(e||new Sn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+_e),(e||new Sn).__init(t.readInt32(t.position())+t.position(),t)}version(){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):je.V1}headerType(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):me.NONE}header(t){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}bodyLength(){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}customMetadata(t,e){const n=this.bb.__offset(this.bb_pos,12);return n?(e||new qe).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}customMetadataLength(){const t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startMessage(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,je.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,me.NONE)}static addHeader(t,e){t.addFieldOffset(2,e,0)}static addBodyLength(t,e){t.addFieldInt64(3,e,BigInt("0"))}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endMessage(t){return t.endObject()}static finishMessageBuffer(t,e){t.finish(e)}static finishSizePrefixedMessageBuffer(t,e){t.finish(e,void 0,!0)}static createMessage(t,e,n,i,s,o){return Sn.startMessage(t),Sn.addVersion(t,e),Sn.addHeaderType(t,n),Sn.addHeader(t,i),Sn.addBodyLength(t,s),Sn.addCustomMetadata(t,o),Sn.endMessage(t)}};class R2 extends se{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return oy.startNull(e),oy.endNull(e)}visitInt(t,e){return Cr.startInt(e),Cr.addBitWidth(e,t.bitWidth),Cr.addIsSigned(e,t.isSigned),Cr.endInt(e)}visitFloat(t,e){return Rn.startFloatingPoint(e),Rn.addPrecision(e,t.precision),Rn.endFloatingPoint(e)}visitBinary(t,e){return ey.startBinary(e),ey.endBinary(e)}visitLargeBinary(t,e){return ny.startLargeBinary(e),ny.endLargeBinary(e)}visitBool(t,e){return ry.startBool(e),ry.endBool(e)}visitUtf8(t,e){return ay.startUtf8(e),ay.endUtf8(e)}visitLargeUtf8(t,e){return iy.startLargeUtf8(e),iy.endLargeUtf8(e)}visitDecimal(t,e){return Js.startDecimal(e),Js.addScale(e,t.scale),Js.addPrecision(e,t.precision),Js.addBitWidth(e,t.bitWidth),Js.endDecimal(e)}visitDate(t,e){return Vl.startDate(e),Vl.addUnit(e,t.unit),Vl.endDate(e)}visitTime(t,e){return Zr.startTime(e),Zr.addUnit(e,t.unit),Zr.addBitWidth(e,t.bitWidth),Zr.endTime(e)}visitTimestamp(t,e){const n=t.timezone&&e.createString(t.timezone)||void 0;return Kr.startTimestamp(e),Kr.addUnit(e,t.unit),n!==void 0&&Kr.addTimezone(e,n),Kr.endTimestamp(e)}visitInterval(t,e){return Fn.startInterval(e),Fn.addUnit(e,t.unit),Fn.endInterval(e)}visitDuration(t,e){return jl.startDuration(e),jl.addUnit(e,t.unit),jl.endDuration(e)}visitList(t,e){return sy.startList(e),sy.endList(e)}visitStruct(t,e){return ys.startStruct_(e),ys.endStruct_(e)}visitUnion(t,e){vr.startTypeIdsVector(e,t.typeIds.length);const n=vr.createTypeIdsVector(e,t.typeIds);return vr.startUnion(e),vr.addMode(e,t.mode),vr.addTypeIds(e,n),vr.endUnion(e)}visitDictionary(t,e){const n=this.visit(t.indices,e);return ai.startDictionaryEncoding(e),ai.addId(e,BigInt(t.id)),ai.addIsOrdered(e,t.isOrdered),n!==void 0&&ai.addIndexType(e,n),ai.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return $l.startFixedSizeBinary(e),$l.addByteWidth(e,t.byteWidth),$l.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return Gl.startFixedSizeList(e),Gl.addListSize(e,t.listSize),Gl.endFixedSizeList(e)}visitMap(t,e){return Wl.startMap(e),Wl.addKeysSorted(e,t.keysSorted),Wl.endMap(e)}}const Rh=new R2;function F2(r,t=new Map){return new Le(L2(r,t),Yl(r.metadata),t)}function Sx(r){return new Br(r.count,Tx(r.columns),Ix(r.columns))}function D2(r){return new Vn(Sx(r.data),r.id,r.isDelta)}function L2(r,t){return(r.fields||[]).filter(Boolean).map(e=>Pe.fromJSON(e,t))}function yy(r,t){return(r.children||[]).filter(Boolean).map(e=>Pe.fromJSON(e,t))}function Tx(r){return(r||[]).reduce((t,e)=>[...t,new Ni(e.count,N2(e.VALIDITY)),...Tx(e.children)],[])}function Ix(r,t=[]){for(let e=-1,n=(r||[]).length;++et+ +(e===0),0)}function B2(r,t){let e,n,i,s,o,a;return!t||!(s=r.dictionary)?(o=_y(r,yy(r,t)),i=new Pe(r.name,o,r.nullable,Yl(r.metadata))):t.has(e=s.id)?(n=(n=s.indexType)?vy(n):new za,a=new Oo(t.get(e),n,e,s.isOrdered),i=new Pe(r.name,a,r.nullable,Yl(r.metadata))):(n=(n=s.indexType)?vy(n):new za,t.set(e,o=_y(r,yy(r,t))),a=new Oo(o,n,e,s.isOrdered),i=new Pe(r.name,a,r.nullable,Yl(r.metadata))),i||null}function Yl(r=[]){return new Map(r.map(({key:t,value:e})=>[t,e]))}function vy(r){return new Es(r.isSigned,r.bitWidth)}function _y(r,t){const e=r.type.name;switch(e){case"NONE":return new Ri;case"null":return new Ri;case"binary":return new gu;case"largebinary":return new yu;case"utf8":return new vu;case"largeutf8":return new _u;case"bool":return new bu;case"list":return new Au((t||[])[0]);case"struct":return new dr(t||[]);case"struct_":return new dr(t||[])}switch(e){case"int":{const n=r.type;return new Es(n.isSigned,n.bitWidth)}case"floatingpoint":{const n=r.type;return new mu(ar[n.precision])}case"decimal":{const n=r.type;return new wu(n.scale,n.precision,n.bitWidth)}case"date":{const n=r.type;return new xu(nn[n.unit])}case"time":{const n=r.type;return new Su(Vt[n.unit],n.bitWidth)}case"timestamp":{const n=r.type;return new Tu(Vt[n.unit],n.timezone)}case"interval":{const n=r.type;return new Iu(zn[n.unit])}case"duration":{const n=r.type;return new Eu(Vt[n.unit])}case"union":{const n=r.type,[i,...s]=(n.mode+"").toLowerCase(),o=i.toUpperCase()+s.join("");return new Mu(lr[o],n.typeIds||[],t||[])}case"fixedsizebinary":{const n=r.type;return new Cu(n.byteWidth)}case"fixedsizelist":{const n=r.type;return new Ou(n.listSize,(t||[])[0])}case"map":{const n=r.type;return new Pu((t||[])[0],n.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var U2=kb,k2=Mo;class fr{static fromJSON(t,e){const n=new fr(0,je.V5,e);return n._createHeader=z2(t,e),n}static decode(t){t=new k2(ce(t));const e=bi.getRootAsMessage(t),n=e.bodyLength(),i=e.version(),s=e.headerType(),o=new fr(n,i,s);return o._createHeader=V2(e,s),o}static encode(t){const e=new U2;let n=-1;return t.isSchema()?n=Le.encode(e,t.header()):t.isRecordBatch()?n=Br.encode(e,t.header()):t.isDictionaryBatch()&&(n=Vn.encode(e,t.header())),bi.startMessage(e),bi.addVersion(e,je.V5),bi.addHeader(e,n),bi.addHeaderType(e,t.headerType),bi.addBodyLength(e,BigInt(t.bodyLength)),bi.finishMessageBuffer(e,bi.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof Le)return new fr(0,je.V5,me.Schema,t);if(t instanceof Br)return new fr(e,je.V5,me.RecordBatch,t);if(t instanceof Vn)return new fr(e,je.V5,me.DictionaryBatch,t);throw new Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===me.Schema}isRecordBatch(){return this.headerType===me.RecordBatch}isDictionaryBatch(){return this.headerType===me.DictionaryBatch}constructor(t,e,n,i){this._version=e,this._headerType=n,this.body=new Uint8Array(0),i&&(this._createHeader=()=>i),this._bodyLength=Te(t)}}class Br{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,n){this._nodes=e,this._buffers=n,this._length=Te(t)}}class Vn{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(t,e,n=!1){this._data=t,this._isDelta=n,this._id=Te(e)}}class Ln{constructor(t,e){this.offset=Te(t),this.length=Te(e)}}class Ni{constructor(t,e){this.length=Te(t),this.nullCount=Te(e)}}function z2(r,t){return()=>{switch(t){case me.Schema:return Le.fromJSON(r);case me.RecordBatch:return Br.fromJSON(r);case me.DictionaryBatch:return Vn.fromJSON(r)}throw new Error(`Unrecognized Message type: { name: ${me[t]}, type: ${t} }`)}}function V2(r,t){return()=>{switch(t){case me.Schema:return Le.decode(r.header(new In),new Map,r.version());case me.RecordBatch:return Br.decode(r.header(new ri),r.version());case me.DictionaryBatch:return Vn.decode(r.header(new Zs),r.version())}throw new Error(`Unrecognized Message type: { name: ${me[t]}, type: ${t} }`)}}Pe.encode=K2;Pe.decode=Q2;Pe.fromJSON=B2;Le.encode=Z2;Le.decode=j2;Le.fromJSON=F2;Br.encode=J2;Br.decode=$2;Br.fromJSON=Sx;Vn.encode=tD;Vn.decode=G2;Vn.fromJSON=D2;Ni.encode=eD;Ni.decode=H2;Ln.encode=rD;Ln.decode=W2;function j2(r,t=new Map,e=je.V5){const n=q2(r,t);return new Le(n,ql(r),t,e)}function $2(r,t=je.V5){if(r.compression()!==null)throw new Error("Record batch compression not implemented");return new Br(r.length(),X2(r),Y2(r,t))}function G2(r,t=je.V5){return new Vn(Br.decode(r.data(),t),r.id(),r.isDelta())}function W2(r){return new Ln(r.offset(),r.length())}function H2(r){return new Ni(r.length(),r.nullCount())}function X2(r){const t=[];for(let e,n=-1,i=-1,s=r.nodesLength();++nPe.encode(r,s));In.startFieldsVector(r,e.length);const n=In.createFieldsVector(r,e),i=t.metadata&&t.metadata.size>0?In.createCustomMetadataVector(r,[...t.metadata].map(([s,o])=>{const a=r.createString(`${s}`),l=r.createString(`${o}`);return qe.startKeyValue(r),qe.addKey(r,a),qe.addValue(r,l),qe.endKeyValue(r)})):-1;return In.startSchema(r),In.addFields(r,n),In.addEndianness(r,nD?Co.Little:Co.Big),i!==-1&&In.addCustomMetadata(r,i),In.endSchema(r)}function K2(r,t){let e=-1,n=-1,i=-1;const s=t.type;let o=t.typeId;Ot.isDictionary(s)?(o=s.dictionary.typeId,i=Rh.visit(s,r),n=Rh.visit(s.dictionary,r)):n=Rh.visit(s,r);const a=(s.children||[]).map(c=>Pe.encode(r,c)),l=Wr.createChildrenVector(r,a),u=t.metadata&&t.metadata.size>0?Wr.createCustomMetadataVector(r,[...t.metadata].map(([c,h])=>{const f=r.createString(`${c}`),d=r.createString(`${h}`);return qe.startKeyValue(r),qe.addKey(r,f),qe.addValue(r,d),qe.endKeyValue(r)})):-1;return t.name&&(e=r.createString(t.name)),Wr.startField(r),Wr.addType(r,n),Wr.addTypeType(r,o),Wr.addChildren(r,l),Wr.addNullable(r,!!t.nullable),e!==-1&&Wr.addName(r,e),i!==-1&&Wr.addDictionary(r,i),u!==-1&&Wr.addCustomMetadata(r,u),Wr.endField(r)}function J2(r,t){const e=t.nodes||[],n=t.buffers||[];ri.startNodesVector(r,e.length);for(const o of e.slice().reverse())Ni.encode(r,o);const i=r.endVector();ri.startBuffersVector(r,n.length);for(const o of n.slice().reverse())Ln.encode(r,o);const s=r.endVector();return ri.startRecordBatch(r),ri.addLength(r,BigInt(t.length)),ri.addNodes(r,i),ri.addBuffers(r,s),ri.endRecordBatch(r)}function tD(r,t){const e=Br.encode(r,t.data);return Zs.startDictionaryBatch(r),Zs.addId(r,BigInt(t.id)),Zs.addIsDelta(r,t.isDelta),Zs.addData(r,e),Zs.endDictionaryBatch(r)}function eD(r,t){return jb.createFieldNode(r,BigInt(t.length),BigInt(t.nullCount))}function rD(r,t){return Vb.createBuffer(r,BigInt(t.offset),BigInt(t.length))}const nD=(()=>{const r=new ArrayBuffer(2);return new DataView(r).setInt16(0,256,!0),new Int16Array(r)[0]===256})(),fp=r=>`Expected ${me[r]} Message in stream, but was null or length 0.`,pp=r=>`Header pointer of flatbuffer-encoded ${me[r]} Message is null or length 0.`,Ex=(r,t)=>`Expected to read ${r} metadata bytes, but only read ${t}.`,Ax=(r,t)=>`Expected to read ${r} bytes for message body, but only read ${t}.`;class Mx{constructor(t){this.source=t instanceof Nu?t:new Nu(t)}[Symbol.iterator](){return this}next(){let t;return(t=this.readMetadataLength()).done||t.value===-1&&(t=this.readMetadataLength()).done||(t=this.readMetadata(t.value)).done?Be:t}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(fp(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);const e=ce(this.source.read(t));if(e.byteLength[...i,...s.VALIDITY&&[s.VALIDITY]||[],...s.TYPE_ID&&[s.TYPE_ID]||[],...s.OFFSET&&[s.OFFSET]||[],...s.DATA&&[s.DATA]||[],...e(s.children)],[])}}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(fp(t));return e.value}readSchema(){const t=me.Schema,e=this.readMessage(t),n=e==null?void 0:e.header();if(!e||!n)throw new Error(pp(t));return n}}const uc=4,sf="ARROW1",ja=new Uint8Array(sf.length);for(let r=0;rthis):this}readRecordBatch(t){return this._impl.isFile()?this._impl.readRecordBatch(t):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return Yr.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return Yr.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}static from(t){return t instanceof tn?t:Hd(t)?cD(t):Fb(t)?fD(t):Is(t)?Jt(this,void 0,void 0,function*(){return yield tn.from(yield t)}):Db(t)||Zf(t)||Lb(t)||Uo(t)?dD(new Po(t)):hD(new Nu(t))}static readAll(t){return t instanceof tn?t.isSync()?Sy(t):Ty(t):Hd(t)||ArrayBuffer.isView(t)||Qa(t)||Rb(t)?Sy(t):Ty(t)}}class Uu extends tn{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return br(this,arguments,function*(){yield Rt(yield*Ss(Bn(this[Symbol.iterator]())))})}}class ku extends tn{constructor(t){super(t),this._impl=t}readAll(){return Jt(this,void 0,void 0,function*(){var t,e,n,i;const s=new Array;try{for(var o=!0,a=Bn(this),l;l=yield a.next(),t=l.done,!t;o=!0){i=l.value,o=!1;const u=i;s.push(u)}}catch(u){e={error:u}}finally{try{!o&&!t&&(n=a.return)&&(yield n.call(a))}finally{if(e)throw e.error}}return s})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}}class Ox extends Uu{constructor(t){super(t),this._impl=t}}class aD extends ku{constructor(t){super(t),this._impl=t}}class Px{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(t=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=t}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(t){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=t,this.dictionaries=new Map,this}_loadRecordBatch(t,e){const n=this._loadVectors(t,e,this.schema.fields),i=le({type:new dr(this.schema.fields),length:t.length,children:n});return new _r(this.schema,i)}_loadDictionaryBatch(t,e){const{id:n,isDelta:i}=t,{dictionaries:s,schema:o}=this,a=s.get(n),l=o.dictionaries.get(n),u=this._loadVectors(t.data,e,[l]);return(a&&i?a.concat(new Ne(u)):new Ne(u)).memoize()}_loadVectors(t,e,n){return new _x(e,t.nodes,t.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(n)}}class zu extends Px{constructor(t,e){super(e),this._reader=Hd(t)?new sD(this._handle=t):new Mx(this._handle=t)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(t){return this.closed||(this.autoDestroy=Fx(this,t),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(t):Be}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):Be}next(){if(this.closed)return Be;let t;const{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;const n=t.header(),i=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(n,i)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const n=t.header(),i=e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(n,i);this.dictionaries.set(n.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new dp(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}}class Vu extends Px{constructor(t,e){super(e),this._reader=new iD(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Jt(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(t){return Jt(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=Fx(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return Jt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):Be})}return(t){return Jt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):Be})}next(){return Jt(this,void 0,void 0,function*(){if(this.closed)return Be;let t;const{_reader:e}=this;for(;t=yield this._readNextMessageAndValidate();)if(t.isSchema())yield this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;const n=t.header(),i=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(n,i)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const n=t.header(),i=yield e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(n,i);this.dictionaries.set(n.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new dp(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return Jt(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}}class Rx extends zu{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,e){super(t instanceof my?t:new my(t),e)}isSync(){return!0}isFile(){return!0}open(t){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(const e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(t)}readRecordBatch(t){var e;if(this.closed)return null;this._footer||this.open();const n=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(n&&this._handle.seek(n.offset)){const i=this._reader.readMessage(me.RecordBatch);if(i!=null&&i.isRecordBatch()){const s=i.header(),o=this._reader.readMessageBody(i.bodyLength);return this._loadRecordBatch(s,o)}}return null}_readDictionaryBatch(t){var e;const n=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(n&&this._handle.seek(n.offset)){const i=this._reader.readMessage(me.DictionaryBatch);if(i!=null&&i.isDictionaryBatch()){const s=i.header(),o=this._reader.readMessageBody(i.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}}_readFooter(){const{_handle:t}=this,e=t.size-Cx,n=t.readInt32(e),i=t.readAt(e-n,n);return Va.decode(i)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Jt(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const n of this._footer.dictionaryBatches())n&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){return Jt(this,void 0,void 0,function*(){var e;if(this.closed)return null;this._footer||(yield this.open());const n=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(n&&(yield this._handle.seek(n.offset))){const i=yield this._reader.readMessage(me.RecordBatch);if(i!=null&&i.isRecordBatch()){const s=i.header(),o=yield this._reader.readMessageBody(i.bodyLength);return this._loadRecordBatch(s,o)}}return null})}_readDictionaryBatch(t){return Jt(this,void 0,void 0,function*(){var e;const n=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(n&&(yield this._handle.seek(n.offset))){const i=yield this._reader.readMessage(me.DictionaryBatch);if(i!=null&&i.isDictionaryBatch()){const s=i.header(),o=yield this._reader.readMessageBody(i.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}})}_readFooter(){return Jt(this,void 0,void 0,function*(){const{_handle:t}=this;t._pending&&(yield t._pending);const e=t.size-Cx,n=yield t.readInt32(e),i=yield t.readAt(e-n,n);return Va.decode(i)})}_readNextMessageAndValidate(t){return Jt(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?mp(t)?new Ox(new Rx(r.read())):new Uu(new zu(r)):new Uu(new zu(function*(){}()))}function dD(r){return Jt(this,void 0,void 0,function*(){const t=yield r.peek(tl+7&-8);return t&&t.byteLength>=4?mp(t)?new Ox(new Rx(yield r.read())):new ku(new Vu(r)):new ku(new Vu(function(){return br(this,arguments,function*(){})}()))})}function fD(r){return Jt(this,void 0,void 0,function*(){const{size:t}=yield r.stat(),e=new Bu(r,t);return t>=oD&&mp(yield e.readAt(0,tl+7&-8))?new aD(new lD(e)):new ku(new Vu(e))})}class ke extends se{static assemble(...t){const e=i=>i.flatMap(s=>Array.isArray(s)?e(s):s instanceof _r?s.data.children:s.data),n=new ke;return n.visitMany(e(t)),n}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof Ne)return this.visitMany(t.data),this;const{type:e}=t;if(!Ot.isDictionary(e)){const{length:n}=t;if(n>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");if(Ot.isUnion(e))this.nodes.push(new Ni(n,0));else{const{nullCount:i}=t;Ot.isNull(e)||dn.call(this,i<=0?new Uint8Array(0):Ru(t.offset,n,t.nullBitmap)),this.nodes.push(new Ni(n,i))}}return super.visit(t)}visitNull(t){return this}visitDictionary(t){return this.visit(t.clone(t.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}}function dn(r){const t=r.byteLength+7&-8;return this.buffers.push(r),this.bufferRegions.push(new Ln(this._byteLength,t)),this._byteLength+=t,this}function pD(r){var t;const{type:e,length:n,typeIds:i,valueOffsets:s}=r;if(dn.call(this,i),e.mode===lr.Sparse)return of.call(this,r);if(e.mode===lr.Dense){if(r.offset<=0)return dn.call(this,s),of.call(this,r);{const o=new Int32Array(n),a=Object.create(null),l=Object.create(null);for(let u,c,h=-1;++h{const h=e.typeIds[c],f=a[h],d=l[h];return u.slice(f,Math.min(n,d))}))}}return this}function mD(r){let t;return r.nullCount>=r.length?dn.call(this,new Uint8Array(0)):(t=r.values)instanceof Uint8Array?dn.call(this,Ru(r.offset,r.length,t)):dn.call(this,Fu(r.values))}function fi(r){return dn.call(this,r.values.subarray(0,r.length*r.stride))}function cc(r){const{length:t,values:e,valueOffsets:n}=r,i=Te(n[0]),s=Te(n[t]),o=Math.min(s-i,e.byteLength-i);return dn.call(this,Bb(-i,t+1,n)),dn.call(this,e.subarray(i,i+o)),this}function gp(r){const{length:t,valueOffsets:e}=r;if(e){const{[0]:n,[t]:i}=e;return dn.call(this,Bb(-n,t+1,e)),this.visit(r.children[0].slice(n,i-n))}return this.visit(r.children[0])}function of(r){return this.visitMany(r.type.children.map((t,e)=>r.children[e]).filter(Boolean))[0]}ke.prototype.visitBool=mD;ke.prototype.visitInt=fi;ke.prototype.visitFloat=fi;ke.prototype.visitUtf8=cc;ke.prototype.visitLargeUtf8=cc;ke.prototype.visitBinary=cc;ke.prototype.visitLargeBinary=cc;ke.prototype.visitFixedSizeBinary=fi;ke.prototype.visitDate=fi;ke.prototype.visitTimestamp=fi;ke.prototype.visitTime=fi;ke.prototype.visitDecimal=fi;ke.prototype.visitList=gp;ke.prototype.visitStruct=of;ke.prototype.visitUnion=pD;ke.prototype.visitInterval=fi;ke.prototype.visitDuration=fi;ke.prototype.visitFixedSizeList=gp;ke.prototype.visitMap=gp;class Dx extends ap{static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}constructor(t){super(),this._position=0,this._started=!1,this._sink=new Xl,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,wr(t)||(t={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof t.autoDestroy=="boolean"?t.autoDestroy:!0,this._writeLegacyIpcFormat=typeof t.writeLegacyIpcFormat=="boolean"?t.writeLegacyIpcFormat:!1}toString(t=!1){return this._sink.toString(t)}toUint8Array(t=!1){return this._sink.toUint8Array(t)}writeAll(t){return Is(t)?t.then(e=>this.writeAll(e)):Uo(t)?bp(this,t):_p(this,t)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(t){return this._sink.toDOMStream(t)}toNodeStream(t){return this._sink.toNodeStream(t)}close(){return this.reset()._sink.close()}abort(t){return this.reset()._sink.abort(t)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(t=this._sink,e=null){return t===this._sink||t instanceof Xl?this._sink=t:(this._sink=new Xl,t&&GR(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&WR(t)&&this.toNodeStream({objectMode:!1}).pipe(t)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,(!e||!nf(e,this._schema))&&(e==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=e,this._writeSchema(e))),this}write(t){let e=null;if(this._sink){if(t==null)return this.finish()&&void 0;if(t instanceof Li&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof _r&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!nf(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof _r?t instanceof dp||this._writeRecordBatch(t):t instanceof Li?this.writeAll(t.batches):Qa(t)&&this.writeAll(t)}_writeMessage(t,e=8){const n=e-1,i=fr.encode(t),s=i.byteLength,o=this._writeLegacyIpcFormat?4:8,a=s+o+n&~n,l=a-s-o;return t.headerType===me.RecordBatch?this._recordBatchBlocks.push(new Fi(a,t.bodyLength,this._position)):t.headerType===me.DictionaryBatch&&this._dictionaryBlocks.push(new Fi(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-o)),s>0&&this._write(i),this._writePadding(l)}_write(t){if(this._started){const e=ce(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(fr.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(ja)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){const{byteLength:e,nodes:n,bufferRegions:i,buffers:s}=ke.assemble(t),o=new Br(t.numRows,n,i),a=fr.from(o,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(s)}_writeDictionaryBatch(t,e,n=!1){const{byteLength:i,nodes:s,bufferRegions:o,buffers:a}=ke.assemble(new Ne([t])),l=new Br(t.length,s,o),u=new Vn(l,e,n),c=fr.from(u,i);return this._writeMessage(c)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,n,i;for(let s=-1,o=t.length;++s0&&(this._write(e),(i=(n+7&-8)-n)>0&&this._writePadding(i));return this}_writeDictionaries(t){var e,n;for(const[i,s]of t.dictionaries){const o=(e=s==null?void 0:s.data)!==null&&e!==void 0?e:[],a=this._seenDictionaries.get(i),l=(n=this._dictionaryDeltaOffsets.get(i))!==null&&n!==void 0?n:0;if(!a||a.data[0]!==o[0])for(const[u,c]of o.entries())this._writeDictionaryBatch(c,i,u>0);else if(ln.writeAll(i)):Uo(t)?bp(n,t):_p(n,t)}}class vp extends Dx{static writeAll(t){const e=new vp;return Is(t)?t.then(n=>e.writeAll(n)):Uo(t)?bp(e,t):_p(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(t,e,n=!1){if(!n&&this._seenDictionaries.has(e))throw new Error("The Arrow File format does not support replacement dictionaries. ");return super._writeDictionaryBatch(t,e,n)}_writeFooter(t){const e=Va.encode(new Va(t,je.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}}function _p(r,t){let e=t;t instanceof Li&&(e=t.batches,r.reset(void 0,t.schema));for(const n of e)r.write(n);return r.finish()}function bp(r,t){return Jt(this,void 0,void 0,function*(){var e,n,i,s,o,a,l;try{for(e=!0,n=Bn(t);i=yield n.next(),s=i.done,!s;e=!0){l=i.value,e=!1;const u=l;r.write(u)}}catch(u){o={error:u}}finally{try{!e&&!s&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return r.finish()})}function gD(r,t="stream"){return(t==="stream"?yp:vp).writeAll(r).toUint8Array(!0)}var yD=Object.create,Lx=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,_D=Object.getOwnPropertyNames,bD=Object.getPrototypeOf,wD=Object.prototype.hasOwnProperty,xD=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),SD=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _D(t))!wD.call(r,i)&&i!==e&&Lx(r,i,{get:()=>t[i],enumerable:!(n=vD(t,i))||n.enumerable});return r},TD=(r,t,e)=>(e=r!=null?yD(bD(r)):{},SD(!r||!r.__esModule?Lx(e,"default",{value:r,enumerable:!0}):e,r)),ID=xD((r,t)=>{t.exports=Worker}),Nx=(r=>(r[r.UNDEFINED=0]="UNDEFINED",r[r.AUTOMATIC=1]="AUTOMATIC",r[r.READ_ONLY=2]="READ_ONLY",r[r.READ_WRITE=3]="READ_WRITE",r))(Nx||{}),ED=(r=>(r[r.IDENTIFIER=0]="IDENTIFIER",r[r.NUMERIC_CONSTANT=1]="NUMERIC_CONSTANT",r[r.STRING_CONSTANT=2]="STRING_CONSTANT",r[r.OPERATOR=3]="OPERATOR",r[r.KEYWORD=4]="KEYWORD",r[r.COMMENT=5]="COMMENT",r))(ED||{}),AD=(r=>(r[r.NONE=0]="NONE",r[r.DEBUG=1]="DEBUG",r[r.INFO=2]="INFO",r[r.WARNING=3]="WARNING",r[r.ERROR=4]="ERROR",r))(AD||{}),MD=(r=>(r[r.NONE=0]="NONE",r[r.CONNECT=1]="CONNECT",r[r.DISCONNECT=2]="DISCONNECT",r[r.OPEN=3]="OPEN",r[r.QUERY=4]="QUERY",r[r.INSTANTIATE=5]="INSTANTIATE",r))(MD||{}),CD=(r=>(r[r.NONE=0]="NONE",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR",r[r.START=3]="START",r[r.RUN=4]="RUN",r[r.CAPTURE=5]="CAPTURE",r))(CD||{}),OD=(r=>(r[r.NONE=0]="NONE",r[r.WEB_WORKER=1]="WEB_WORKER",r[r.NODE_WORKER=2]="NODE_WORKER",r[r.BINDINGS=3]="BINDINGS",r[r.ASYNC_DUCKDB=4]="ASYNC_DUCKDB",r))(OD||{}),PD=class{log(r){}},Bx=class{constructor(r=2){this.level=r}log(r){r.level>=this.level&&console.log(r)}},RD=(r=>(r[r.SUCCESS=0]="SUCCESS",r))(RD||{}),FD=class{constructor(r,t){this._bindings=r,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(r){return r(this._bindings,this._conn)}async query(r){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let t=await this._bindings.runQuery(this._conn,r),e=tn.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new Li(e)}async send(r,t=!1){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let e=await this._bindings.startPendingQuery(this._conn,r,t);for(;e==null;)e=await this._bindings.pollPendingQuery(this._conn);let n=new Ux(this._bindings,this._conn,e),i=await tn.from(n);return console.assert(i.isAsync()),console.assert(i.isStream()),i}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(r){return await this._bindings.getTableNames(this._conn,r)}async prepare(r){let t=await this._bindings.createPrepared(this._conn,r);return new DD(this._bindings,this._conn,t)}async insertArrowTable(r,t){let e=gD(r,"stream");await this.insertArrowFromIPCStream(e,t)}async insertArrowFromIPCStream(r,t){await this._bindings.insertArrowFromIPCStream(this._conn,r,t)}async insertCSVFromPath(r,t){await this._bindings.insertCSVFromPath(this._conn,r,t)}async insertJSONFromPath(r,t){await this._bindings.insertJSONFromPath(this._conn,r,t)}},Ux=class{constructor(r,t,e){this.db=r,this.conn=t,this.header=e,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let r;return this._inFlight!=null?(r=await this._inFlight,this._inFlight=null):r=await this.db.fetchQueryResults(this.conn),this._depleted=r.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:r}}[Symbol.asyncIterator](){return this}},DD=class{constructor(r,t,e){this.bindings=r,this.connectionId=t,this.statementId=e}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...r){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,r),e=tn.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new Li(e)}async send(...r){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,r),e=new Ux(this.bindings,this.connectionId,t),n=await tn.from(e);return console.assert(n.isAsync()),console.assert(n.isStream()),n}},LD=(r=>(r.CANCEL_PENDING_QUERY="CANCEL_PENDING_QUERY",r.CLOSE_PREPARED="CLOSE_PREPARED",r.COLLECT_FILE_STATISTICS="COLLECT_FILE_STATISTICS",r.REGISTER_OPFS_FILE_NAME="REGISTER_OPFS_FILE_NAME",r.CONNECT="CONNECT",r.COPY_FILE_TO_BUFFER="COPY_FILE_TO_BUFFER",r.COPY_FILE_TO_PATH="COPY_FILE_TO_PATH",r.CREATE_PREPARED="CREATE_PREPARED",r.DISCONNECT="DISCONNECT",r.DROP_FILE="DROP_FILE",r.DROP_FILES="DROP_FILES",r.EXPORT_FILE_STATISTICS="EXPORT_FILE_STATISTICS",r.FETCH_QUERY_RESULTS="FETCH_QUERY_RESULTS",r.FLUSH_FILES="FLUSH_FILES",r.GET_FEATURE_FLAGS="GET_FEATURE_FLAGS",r.GET_TABLE_NAMES="GET_TABLE_NAMES",r.GET_VERSION="GET_VERSION",r.GLOB_FILE_INFOS="GLOB_FILE_INFOS",r.INSERT_ARROW_FROM_IPC_STREAM="INSERT_ARROW_FROM_IPC_STREAM",r.INSERT_CSV_FROM_PATH="IMPORT_CSV_FROM_PATH",r.INSERT_JSON_FROM_PATH="IMPORT_JSON_FROM_PATH",r.INSTANTIATE="INSTANTIATE",r.OPEN="OPEN",r.PING="PING",r.POLL_PENDING_QUERY="POLL_PENDING_QUERY",r.REGISTER_FILE_BUFFER="REGISTER_FILE_BUFFER",r.REGISTER_FILE_HANDLE="REGISTER_FILE_HANDLE",r.REGISTER_FILE_URL="REGISTER_FILE_URL",r.RESET="RESET",r.RUN_PREPARED="RUN_PREPARED",r.RUN_QUERY="RUN_QUERY",r.SEND_PREPARED="SEND_PREPARED",r.START_PENDING_QUERY="START_PENDING_QUERY",r.TOKENIZE="TOKENIZE",r))(LD||{}),ND=(r=>(r.CONNECTION_INFO="CONNECTION_INFO",r.ERROR="ERROR",r.FEATURE_FLAGS="FEATURE_FLAGS",r.FILE_BUFFER="FILE_BUFFER",r.FILE_INFOS="FILE_INFOS",r.FILE_SIZE="FILE_SIZE",r.FILE_STATISTICS="FILE_STATISTICS",r.INSTANTIATE_PROGRESS="INSTANTIATE_PROGRESS",r.LOG="LOG",r.OK="OK",r.PREPARED_STATEMENT_ID="PREPARED_STATEMENT_ID",r.QUERY_PLAN="QUERY_PLAN",r.QUERY_RESULT="QUERY_RESULT",r.QUERY_RESULT_CHUNK="QUERY_RESULT_CHUNK",r.QUERY_RESULT_HEADER="QUERY_RESULT_HEADER",r.QUERY_RESULT_HEADER_OR_NULL="QUERY_RESULT_HEADER_OR_NULL",r.REGISTERED_FILE="REGISTERED_FILE",r.SCRIPT_TOKENS="SCRIPT_TOKENS",r.SUCCESS="SUCCESS",r.TABLE_NAMES="TABLE_NAMES",r.VERSION_STRING="VERSION_STRING",r))(ND||{}),de=class{constructor(r,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=r,this.data=t,this.promise=new Promise((e,n)=>{this.promiseResolver=e,this.promiseRejecter=n})}};function Ql(r){switch(r.typeId){case k.Binary:return{sqlType:"binary"};case k.Bool:return{sqlType:"bool"};case k.Date:return{sqlType:"date"};case k.DateDay:return{sqlType:"date32[d]"};case k.DateMillisecond:return{sqlType:"date64[ms]"};case k.Decimal:{let t=r;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case k.Float:return{sqlType:"float"};case k.Float16:return{sqlType:"float16"};case k.Float32:return{sqlType:"float32"};case k.Float64:return{sqlType:"float64"};case k.Int:return{sqlType:"int32"};case k.Int16:return{sqlType:"int16"};case k.Int32:return{sqlType:"int32"};case k.Int64:return{sqlType:"int64"};case k.Uint16:return{sqlType:"uint16"};case k.Uint32:return{sqlType:"uint32"};case k.Uint64:return{sqlType:"uint64"};case k.Uint8:return{sqlType:"uint8"};case k.IntervalDayTime:return{sqlType:"interval[dt]"};case k.IntervalYearMonth:return{sqlType:"interval[m]"};case k.List:return{sqlType:"list",valueType:Ql(r.valueType)};case k.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:r.byteWidth};case k.Null:return{sqlType:"null"};case k.Utf8:return{sqlType:"utf8"};case k.Struct:return{sqlType:"struct",fields:r.children.map(t=>af(t.name,t.type))};case k.Map:{let t=r;return{sqlType:"map",keyType:Ql(t.keyType),valueType:Ql(t.valueType)}}case k.Time:return{sqlType:"time[s]"};case k.TimeMicrosecond:return{sqlType:"time[us]"};case k.TimeMillisecond:return{sqlType:"time[ms]"};case k.TimeNanosecond:return{sqlType:"time[ns]"};case k.TimeSecond:return{sqlType:"time[s]"};case k.Timestamp:return{sqlType:"timestamp",timezone:r.timezone||void 0};case k.TimestampSecond:return{sqlType:"timestamp[s]",timezone:r.timezone||void 0};case k.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:r.timezone||void 0};case k.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:r.timezone||void 0};case k.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:r.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(r.toString()))}function af(r,t){let e=Ql(t);return e.name=r,e}var BD=new TextEncoder,UD=class{constructor(r,t=null){this._onInstantiationProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._logger=r,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}attach(r){this._worker=r,this._worker.addEventListener("message",this._onMessageHandler),this._worker.addEventListener("error",this._onErrorHandler),this._worker.addEventListener("close",this._onCloseHandler),this._workerShutdownPromise=new Promise((t,e)=>{this._workerShutdownResolver=t})}detach(){this._worker&&(this._worker.removeEventListener("message",this._onMessageHandler),this._worker.removeEventListener("error",this._onErrorHandler),this._worker.removeEventListener("close",this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(r,t=[]){if(!this._worker){console.error("cannot send a message since the worker is not set!");return}let e=this._nextMessageId++;return this._pendingRequests.set(e,r),this._worker.postMessage({messageId:e,type:r.type,data:r.data},t),await r.promise}onMessage(r){var t;let e=r.data;switch(e.type){case"LOG":{this._logger.log(e.data);return}case"INSTANTIATE_PROGRESS":{for(let i of this._onInstantiationProgress)i(e.data);return}}let n=this._pendingRequests.get(e.requestId);if(!n){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let i=new Error(e.data.message);i.name=e.data.name,(t=Object.getOwnPropertyDescriptor(i,"stack"))!=null&&t.writable&&(i.stack=e.data.stack),n.promiseRejecter(i);return}switch(n.type){case"CLOSE_PREPARED":case"COLLECT_FILE_STATISTICS":case"REGISTER_OPFS_FILE_NAME":case"COPY_FILE_TO_PATH":case"DISCONNECT":case"DROP_FILE":case"DROP_FILES":case"FLUSH_FILES":case"INSERT_ARROW_FROM_IPC_STREAM":case"IMPORT_CSV_FROM_PATH":case"IMPORT_JSON_FROM_PATH":case"OPEN":case"PING":case"REGISTER_FILE_BUFFER":case"REGISTER_FILE_HANDLE":case"REGISTER_FILE_URL":case"RESET":if(e.type=="OK"){n.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){n.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){n.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){n.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){n.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){n.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){n.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){n.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){n.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){n.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){n.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){n.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){n.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){n.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){n.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){n.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){n.promiseResolver(e.data);return}break}n.promiseRejecter(new Error("unexpected response type: ".concat(e.type.toString())))}onError(r){console.error(r),console.error("error in duckdb worker: ".concat(r.message)),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn("worker terminated with ".concat(this._pendingRequests.size," pending requests"));return}this._pendingRequests.clear()}async reset(){let r=new de("RESET",null);return await this.postTask(r)}async ping(){let r=new de("PING",null);await this.postTask(r)}async dropFile(r){let t=new de("DROP_FILE",r);return await this.postTask(t)}async dropFiles(){let r=new de("DROP_FILES",null);return await this.postTask(r)}async flushFiles(){let r=new de("FLUSH_FILES",null);return await this.postTask(r)}async instantiate(r,t=null,e=n=>{}){this._onInstantiationProgress.push(e);let n=new de("INSTANTIATE",[r,t]);return await this.postTask(n)}async getVersion(){let r=new de("GET_VERSION",null);return await this.postTask(r)}async getFeatureFlags(){let r=new de("GET_FEATURE_FLAGS",null);return await this.postTask(r)}async open(r){let t=new de("OPEN",r);await this.postTask(t)}async tokenize(r){let t=new de("TOKENIZE",r);return await this.postTask(t)}async connectInternal(){let r=new de("CONNECT",null);return await this.postTask(r)}async connect(){let r=await this.connectInternal();return new FD(this,r)}async disconnect(r){let t=new de("DISCONNECT",r);await this.postTask(t)}async runQuery(r,t){let e=new de("RUN_QUERY",[r,t]);return await this.postTask(e)}async startPendingQuery(r,t,e=!1){let n=new de("START_PENDING_QUERY",[r,t,e]);return await this.postTask(n)}async pollPendingQuery(r){let t=new de("POLL_PENDING_QUERY",r);return await this.postTask(t)}async cancelPendingQuery(r){let t=new de("CANCEL_PENDING_QUERY",r);return await this.postTask(t)}async fetchQueryResults(r){let t=new de("FETCH_QUERY_RESULTS",r);return await this.postTask(t)}async getTableNames(r,t){let e=new de("GET_TABLE_NAMES",[r,t]);return await this.postTask(e)}async createPrepared(r,t){let e=new de("CREATE_PREPARED",[r,t]);return await this.postTask(e)}async closePrepared(r,t){let e=new de("CLOSE_PREPARED",[r,t]);await this.postTask(e)}async runPrepared(r,t,e){let n=new de("RUN_PREPARED",[r,t,e]);return await this.postTask(n)}async sendPrepared(r,t,e){let n=new de("SEND_PREPARED",[r,t,e]);return await this.postTask(n)}async globFiles(r){let t=new de("GLOB_FILE_INFOS",r);return await this.postTask(t)}async registerFileText(r,t){let e=BD.encode(t);await this.registerFileBuffer(r,e)}async registerFileURL(r,t,e,n){t===void 0&&(t=r);let i=new de("REGISTER_FILE_URL",[r,t,e,n]);await this.postTask(i)}async registerEmptyFileBuffer(r){}async registerFileBuffer(r,t){let e=new de("REGISTER_FILE_BUFFER",[r,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(r,t,e,n){let i=new de("REGISTER_FILE_HANDLE",[r,t,e,n]);await this.postTask(i,[])}async registerOPFSFileName(r){let t=new de("REGISTER_OPFS_FILE_NAME",[r]);await this.postTask(t,[])}async collectFileStatistics(r,t){let e=new de("COLLECT_FILE_STATISTICS",[r,t]);await this.postTask(e,[])}async exportFileStatistics(r){let t=new de("EXPORT_FILE_STATISTICS",r);return await this.postTask(t,[])}async copyFileToBuffer(r){let t=new de("COPY_FILE_TO_BUFFER",r);return await this.postTask(t)}async copyFileToPath(r,t){let e=new de("COPY_FILE_TO_PATH",[r,t]);await this.postTask(e)}async insertArrowFromIPCStream(r,t,e){if(t.length==0)return;let n=new de("INSERT_ARROW_FROM_IPC_STREAM",[r,t,e]);await this.postTask(n,[t.buffer])}async insertCSVFromPath(r,t,e){if(e.columns!==void 0){let i=[];for(let s in e.columns){let o=e.columns[s];i.push(af(s,o))}e.columnsFlat=i,delete e.columns}let n=new de("IMPORT_CSV_FROM_PATH",[r,t,e]);await this.postTask(n)}async insertJSONFromPath(r,t,e){if(e.columns!==void 0){let i=[];for(let s in e.columns){let o=e.columns[s];i.push(af(s,o))}e.columnsFlat=i,delete e.columns}let n=new de("IMPORT_JSON_FROM_PATH",[r,t,e]);await this.postTask(n)}};function kD(){let r=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),r.decode(t))}kD();var zD=(r=>(r[r.BUFFER=0]="BUFFER",r[r.NODE_FS=1]="NODE_FS",r[r.BROWSER_FILEREADER=2]="BROWSER_FILEREADER",r[r.BROWSER_FSACCESS=3]="BROWSER_FSACCESS",r[r.HTTP=4]="HTTP",r[r.S3=5]="S3",r))(zD||{}),VD=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),jD=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),$D=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),GD=()=>(async r=>{try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(r)}catch{return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),WD={version:"1.29.1-dev68.0"},wp=WD.version.split(".");wp[0];wp[1];wp[2];var HD=()=>typeof navigator>"u",Fh=null,Dh=null,Lh=null,Nh=null,Bh=null;async function XD(){return Fh==null&&(Fh=typeof BigInt64Array<"u"),Dh==null&&(Dh=await jD()),Lh==null&&(Lh=await GD()),Nh==null&&(Nh=await $D()),Bh==null&&(Bh=await VD()),{bigInt64Array:Fh,crossOriginIsolated:HD()||globalThis.crossOriginIsolated||!1,wasmExceptions:Dh,wasmSIMD:Nh,wasmThreads:Lh,wasmBulkMemory:Bh}}async function Iy(r){let t=await XD();if(t.wasmExceptions){if(t.wasmSIMD&&t.wasmThreads&&t.crossOriginIsolated&&r.coi)return{mainModule:r.coi.mainModule,mainWorker:r.coi.mainWorker,pthreadWorker:r.coi.pthreadWorker};if(r.eh)return{mainModule:r.eh.mainModule,mainWorker:r.eh.mainWorker,pthreadWorker:null}}return{mainModule:r.mvp.mainModule,mainWorker:r.mvp.mainWorker,pthreadWorker:null}}TD(ID());const Uh={},wa={};function Ia(r,t){try{const n=(Uh[r]||(Uh[r]=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour:"numeric",timeZoneName:"longOffset"}).format))(t).split("GMT")[1]||"";return n in wa?wa[n]:Ey(n,n.split(":"))}catch{if(r in wa)return wa[r];const e=r==null?void 0:r.match(YD);return e?Ey(r,e.slice(1)):NaN}}const YD=/([+-]\d\d):?(\d\d)?/;function Ey(r,t){const e=+t[0],n=+(t[1]||0);return wa[r]=e>0?e*60+n:e*60-n}class Fr extends Date{constructor(...t){super(),t.length>1&&typeof t[t.length-1]=="string"&&(this.timeZone=t.pop()),this.internal=new Date,isNaN(Ia(this.timeZone,this))?this.setTime(NaN):t.length?typeof t[0]=="number"&&(t.length===1||t.length===2&&typeof t[1]!="number")?this.setTime(t[0]):typeof t[0]=="string"?this.setTime(+new Date(t[0])):t[0]instanceof Date?this.setTime(+t[0]):(this.setTime(+new Date(...t)),kx(this),lf(this)):this.setTime(Date.now())}static tz(t,...e){return e.length?new Fr(...e,t):new Fr(Date.now(),t)}withTimeZone(t){return new Fr(+this,t)}getTimezoneOffset(){return-Ia(this.timeZone,this)}setTime(t){return Date.prototype.setTime.apply(this,arguments),lf(this),+this}[Symbol.for("constructDateFrom")](t){return new Fr(+new Date(t),this.timeZone)}}const Ay=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(r=>{if(!Ay.test(r))return;const t=r.replace(Ay,"$1UTC");Fr.prototype[t]&&(r.startsWith("get")?Fr.prototype[r]=function(){return this.internal[t]()}:(Fr.prototype[r]=function(){return Date.prototype[t].apply(this.internal,arguments),qD(this),+this},Fr.prototype[t]=function(){return Date.prototype[t].apply(this,arguments),lf(this),+this}))});function lf(r){r.internal.setTime(+r),r.internal.setUTCMinutes(r.internal.getUTCMinutes()-r.getTimezoneOffset())}function qD(r){Date.prototype.setFullYear.call(r,r.internal.getUTCFullYear(),r.internal.getUTCMonth(),r.internal.getUTCDate()),Date.prototype.setHours.call(r,r.internal.getUTCHours(),r.internal.getUTCMinutes(),r.internal.getUTCSeconds(),r.internal.getUTCMilliseconds()),kx(r)}function kx(r){const t=Ia(r.timeZone,r),e=new Date(+r);e.setUTCHours(e.getUTCHours()-1);const n=-new Date(+r).getTimezoneOffset(),i=-new Date(+e).getTimezoneOffset(),s=n-i,o=Date.prototype.getHours.apply(r)!==r.internal.getUTCHours();s&&o&&r.internal.setUTCMinutes(r.internal.getUTCMinutes()+s);const a=n-t;a&&Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+a);const l=Ia(r.timeZone,r),c=-new Date(+r).getTimezoneOffset()-l,h=l!==t,f=c-a;if(h&&f){Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+f);const d=Ia(r.timeZone,r),m=l-d;m&&(r.internal.setUTCMinutes(r.internal.getUTCMinutes()+m),Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+m))}}const QD=new TextDecoder("utf-8"),ZD=r=>QD.decode(r),KD=new TextEncoder,zx=r=>KD.encode(r),An=r=>typeof r=="function",el=r=>r!=null&&Object(r)===r,JD=r=>el(r)&&An(r.then),Vx=r=>el(r)&&An(r[Symbol.iterator]),tL=r=>el(r)&&An(r[Symbol.asyncIterator]),eL=r=>el(r)&&"done"in r&&"value"in r,rL=r=>el(r)&&An(r.clear)&&An(r.bytes)&&An(r.position)&&An(r.setPosition)&&An(r.capacity)&&An(r.getBufferIdentifier)&&An(r.createLong),xp=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function nL(r){const t=r[0]?[r[0]]:[];let e,n,i,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let i,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,n);for(const c=e.length;++lur(Int8Array,r),oL=r=>ur(Int16Array,r),aL=r=>ur(Int32Array,r),lL=r=>ur(BigInt64Array,r),uL=r=>ur(Uint8Array,r),cL=r=>ur(Uint16Array,r),hL=r=>ur(Uint32Array,r),dL=r=>ur(BigUint64Array,r),fL=r=>ur(Float32Array,r),pL=r=>ur(Float64Array,r),mL=r=>ur(Uint8ClampedArray,r),cf=r=>(r.next(),r);function*Xn(r,t){const e=function*(i){yield i},n=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof xp?e(t):Vx(t)?t:e(t);return yield*cf(function*(i){let s=null;do s=i.next(yield ur(r,s));while(!s.done)}(n[Symbol.iterator]())),new r}const gL=r=>Xn(Int8Array,r),yL=r=>Xn(Int16Array,r),vL=r=>Xn(Int32Array,r),_L=r=>Xn(Uint8Array,r),bL=r=>Xn(Uint16Array,r),wL=r=>Xn(Uint32Array,r),xL=r=>Xn(Float32Array,r),SL=r=>Xn(Float64Array,r),TL=r=>Xn(Uint8ClampedArray,r);function mn(r,t){return br(this,arguments,function*(){if(JD(t))return yield Rt(yield Rt(yield*Ss(Bn(mn(r,yield Rt(t))))));const n=function(o){return br(this,arguments,function*(){yield yield Rt(yield Rt(o))})},i=function(o){return br(this,arguments,function*(){yield Rt(yield*Ss(Bn(cf(function*(a){let l=null;do l=a.next(yield l==null?void 0:l.value);while(!l.done)}(o[Symbol.iterator]())))))})},s=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof xp?n(t):Vx(t)?i(t):tL(t)?t:n(t);return yield Rt(yield*Ss(Bn(cf(function(o){return br(this,arguments,function*(){let a=null;do a=yield Rt(o.next(yield yield Rt(ur(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Rt(new r)})}const IL=r=>mn(Int8Array,r),EL=r=>mn(Int16Array,r),AL=r=>mn(Int32Array,r),ML=r=>mn(Uint8Array,r),CL=r=>mn(Uint16Array,r),OL=r=>mn(Uint32Array,r),PL=r=>mn(Float32Array,r),RL=r=>mn(Float64Array,r),FL=r=>mn(Uint8ClampedArray,r);function DL(r,t,e){if(r!==0){e=e.slice(0,t);for(let n=-1,i=e.length;++n0)do if(r[e]!==t[e])return!1;while(++eFo(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}const BL=Object.freeze(Object.defineProperty({__proto__:null,valueToString:Fo},Symbol.toStringTag,{value:"Module"}));function pr(r){if(typeof r=="bigint"&&(rNumber.MAX_SAFE_INTEGER))throw new TypeError(`${r} is not safe to convert to a number.`);return Number(r)}function $x(r,t){return pr(r/t)+pr(r%t)/pr(t)}const Gx=Symbol.for("isArrowBigNum");function gn(r,...t){return t.length===0?Object.setPrototypeOf(ur(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}gn.prototype[Gx]=!0;gn.prototype.toJSON=function(){return`"${Do(this)}"`};gn.prototype.valueOf=function(r){return Sp(this,r)};gn.prototype.toString=function(){return Do(this)};gn.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Sp(this);case"string":return Do(this);case"default":return Wx(this)}return Do(this)};function xo(...r){return gn.apply(this,r)}function So(...r){return gn.apply(this,r)}function $a(...r){return gn.apply(this,r)}Object.setPrototypeOf(xo.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(So.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf($a.prototype,Object.create(Uint32Array.prototype));Object.assign(xo.prototype,gn.prototype,{constructor:xo,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(So.prototype,gn.prototype,{constructor:So,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign($a.prototype,gn.prototype,{constructor:$a,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const UL=BigInt(4294967296)*BigInt(4294967296),kL=UL-BigInt(1);function Sp(r,t){const{buffer:e,byteOffset:n,byteLength:i,signed:s}=r,o=new BigUint64Array(e,n,i/8),a=s&&o.at(-1)&BigInt(1)<=0)return kh(r);t=t.slice();let n=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(Ct.prototype);class My extends Ct{constructor(){super(H.Null)}toString(){return"Null"}}Xx=Symbol.toStringTag;My[Xx]=(r=>r[Symbol.toStringTag]="Null")(My.prototype);class Cy extends Ct{constructor(t,e){super(H.Int),this.isSigned=t,this.bitWidth=e}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}}Yx=Symbol.toStringTag;Cy[Yx]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))(Cy.prototype);class Oy extends Ct{constructor(t){super(H.Float),this.precision=t}get ArrayType(){switch(this.precision){case Dr.HALF:return Uint16Array;case Dr.SINGLE:return Float32Array;case Dr.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}qx=Symbol.toStringTag;Oy[qx]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(Oy.prototype);class Py extends Ct{constructor(){super(H.Binary)}toString(){return"Binary"}}Qx=Symbol.toStringTag;Py[Qx]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(Py.prototype);class Ry extends Ct{constructor(){super(H.LargeBinary)}toString(){return"LargeBinary"}}Zx=Symbol.toStringTag;Ry[Zx]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(Ry.prototype);class Fy extends Ct{constructor(){super(H.Utf8)}toString(){return"Utf8"}}Kx=Symbol.toStringTag;Fy[Kx]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(Fy.prototype);class Dy extends Ct{constructor(){super(H.LargeUtf8)}toString(){return"LargeUtf8"}}Jx=Symbol.toStringTag;Dy[Jx]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(Dy.prototype);class Ly extends Ct{constructor(){super(H.Bool)}toString(){return"Bool"}}tS=Symbol.toStringTag;Ly[tS]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(Ly.prototype);class Ny extends Ct{constructor(t,e,n=128){super(H.Decimal),this.scale=t,this.precision=e,this.bitWidth=n}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}eS=Symbol.toStringTag;Ny[eS]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(Ny.prototype);class By extends Ct{constructor(t){super(H.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${Bi[this.unit]}>`}get ArrayType(){return this.unit===Bi.DAY?Int32Array:BigInt64Array}}rS=Symbol.toStringTag;By[rS]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(By.prototype);class Uy extends Ct{constructor(t,e){super(H.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${te[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}nS=Symbol.toStringTag;Uy[nS]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(Uy.prototype);class ky extends Ct{constructor(t,e){super(H.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${te[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}iS=Symbol.toStringTag;ky[iS]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(ky.prototype);class zy extends Ct{constructor(t){super(H.Interval),this.unit=t}toString(){return`Interval<${As[this.unit]}>`}}sS=Symbol.toStringTag;zy[sS]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(zy.prototype);class Vy extends Ct{constructor(t){super(H.Duration),this.unit=t}toString(){return`Duration<${te[this.unit]}>`}}oS=Symbol.toStringTag;Vy[oS]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(Vy.prototype);class jy extends Ct{constructor(t){super(H.List),this.children=[t]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}}aS=Symbol.toStringTag;jy[aS]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(jy.prototype);class hf extends Ct{constructor(t){super(H.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}}lS=Symbol.toStringTag;hf[lS]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(hf.prototype);class $y extends Ct{constructor(t,e,n){super(H.Union),this.mode=t,this.children=n,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((i,s,o)=>(i[s]=o)&&i||i,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}}uS=Symbol.toStringTag;$y[uS]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))($y.prototype);class Gy extends Ct{constructor(t){super(H.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}cS=Symbol.toStringTag;Gy[cS]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(Gy.prototype);class Wy extends Ct{constructor(t,e){super(H.FixedSizeList),this.listSize=t,this.children=[e]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}}hS=Symbol.toStringTag;Wy[hS]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(Wy.prototype);class Hy extends Ct{constructor(t,e=!1){var n,i,s;if(super(H.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((n=t==null?void 0:t.type)===null||n===void 0)&&n.children)){const o=(i=t==null?void 0:t.type)===null||i===void 0?void 0:i.children[0];o&&(o.name="key");const a=(s=t==null?void 0:t.type)===null||s===void 0?void 0:s.children[1];a&&(a.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}}dS=Symbol.toStringTag;Hy[dS]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(Hy.prototype);const VL=(r=>()=>++r)(-1);class Xy extends Ct{constructor(t,e,n,i){super(H.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=i||!1,this.id=n==null?VL():pr(n)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}fS=Symbol.toStringTag;Xy[fS]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(Xy.prototype);function pS(r){const t=r;switch(r.typeId){case H.Decimal:return r.bitWidth/32;case H.Interval:return 1+t.unit;case H.FixedSizeList:return t.listSize;case H.FixedSizeBinary:return t.byteWidth;default:return 1}}class he{visitMany(t,...e){return t.map((n,i)=>this.visit(n,...e.map(s=>s[i])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return jL(this,t,e)}getVisitFnByTypeId(t,e=!0){return ao(this,t,e)}visitNull(t,...e){return null}visitBool(t,...e){return null}visitInt(t,...e){return null}visitFloat(t,...e){return null}visitUtf8(t,...e){return null}visitLargeUtf8(t,...e){return null}visitBinary(t,...e){return null}visitLargeBinary(t,...e){return null}visitFixedSizeBinary(t,...e){return null}visitDate(t,...e){return null}visitTimestamp(t,...e){return null}visitTime(t,...e){return null}visitDecimal(t,...e){return null}visitList(t,...e){return null}visitStruct(t,...e){return null}visitUnion(t,...e){return null}visitDictionary(t,...e){return null}visitInterval(t,...e){return null}visitDuration(t,...e){return null}visitFixedSizeList(t,...e){return null}visitMap(t,...e){return null}}function jL(r,t,e=!0){return typeof t=="number"?ao(r,t,e):typeof t=="string"&&t in H?ao(r,H[t],e):t&&t instanceof Ct?ao(r,Yy(t),e):t!=null&&t.type&&t.type instanceof Ct?ao(r,Yy(t.type),e):ao(r,H.NONE,e)}function ao(r,t,e=!0){let n=null;switch(t){case H.Null:n=r.visitNull;break;case H.Bool:n=r.visitBool;break;case H.Int:n=r.visitInt;break;case H.Int8:n=r.visitInt8||r.visitInt;break;case H.Int16:n=r.visitInt16||r.visitInt;break;case H.Int32:n=r.visitInt32||r.visitInt;break;case H.Int64:n=r.visitInt64||r.visitInt;break;case H.Uint8:n=r.visitUint8||r.visitInt;break;case H.Uint16:n=r.visitUint16||r.visitInt;break;case H.Uint32:n=r.visitUint32||r.visitInt;break;case H.Uint64:n=r.visitUint64||r.visitInt;break;case H.Float:n=r.visitFloat;break;case H.Float16:n=r.visitFloat16||r.visitFloat;break;case H.Float32:n=r.visitFloat32||r.visitFloat;break;case H.Float64:n=r.visitFloat64||r.visitFloat;break;case H.Utf8:n=r.visitUtf8;break;case H.LargeUtf8:n=r.visitLargeUtf8;break;case H.Binary:n=r.visitBinary;break;case H.LargeBinary:n=r.visitLargeBinary;break;case H.FixedSizeBinary:n=r.visitFixedSizeBinary;break;case H.Date:n=r.visitDate;break;case H.DateDay:n=r.visitDateDay||r.visitDate;break;case H.DateMillisecond:n=r.visitDateMillisecond||r.visitDate;break;case H.Timestamp:n=r.visitTimestamp;break;case H.TimestampSecond:n=r.visitTimestampSecond||r.visitTimestamp;break;case H.TimestampMillisecond:n=r.visitTimestampMillisecond||r.visitTimestamp;break;case H.TimestampMicrosecond:n=r.visitTimestampMicrosecond||r.visitTimestamp;break;case H.TimestampNanosecond:n=r.visitTimestampNanosecond||r.visitTimestamp;break;case H.Time:n=r.visitTime;break;case H.TimeSecond:n=r.visitTimeSecond||r.visitTime;break;case H.TimeMillisecond:n=r.visitTimeMillisecond||r.visitTime;break;case H.TimeMicrosecond:n=r.visitTimeMicrosecond||r.visitTime;break;case H.TimeNanosecond:n=r.visitTimeNanosecond||r.visitTime;break;case H.Decimal:n=r.visitDecimal;break;case H.List:n=r.visitList;break;case H.Struct:n=r.visitStruct;break;case H.Union:n=r.visitUnion;break;case H.DenseUnion:n=r.visitDenseUnion||r.visitUnion;break;case H.SparseUnion:n=r.visitSparseUnion||r.visitUnion;break;case H.Dictionary:n=r.visitDictionary;break;case H.Interval:n=r.visitInterval;break;case H.IntervalDayTime:n=r.visitIntervalDayTime||r.visitInterval;break;case H.IntervalYearMonth:n=r.visitIntervalYearMonth||r.visitInterval;break;case H.Duration:n=r.visitDuration;break;case H.DurationSecond:n=r.visitDurationSecond||r.visitDuration;break;case H.DurationMillisecond:n=r.visitDurationMillisecond||r.visitDuration;break;case H.DurationMicrosecond:n=r.visitDurationMicrosecond||r.visitDuration;break;case H.DurationNanosecond:n=r.visitDurationNanosecond||r.visitDuration;break;case H.FixedSizeList:n=r.visitFixedSizeList;break;case H.Map:n=r.visitMap;break}if(typeof n=="function")return n;if(!e)return()=>null;throw new Error(`Unrecognized type '${H[t]}'`)}function Yy(r){switch(r.typeId){case H.Null:return H.Null;case H.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?H.Int8:H.Uint8;case 16:return e?H.Int16:H.Uint16;case 32:return e?H.Int32:H.Uint32;case 64:return e?H.Int64:H.Uint64}return H.Int}case H.Float:switch(r.precision){case Dr.HALF:return H.Float16;case Dr.SINGLE:return H.Float32;case Dr.DOUBLE:return H.Float64}return H.Float;case H.Binary:return H.Binary;case H.LargeBinary:return H.LargeBinary;case H.Utf8:return H.Utf8;case H.LargeUtf8:return H.LargeUtf8;case H.Bool:return H.Bool;case H.Decimal:return H.Decimal;case H.Time:switch(r.unit){case te.SECOND:return H.TimeSecond;case te.MILLISECOND:return H.TimeMillisecond;case te.MICROSECOND:return H.TimeMicrosecond;case te.NANOSECOND:return H.TimeNanosecond}return H.Time;case H.Timestamp:switch(r.unit){case te.SECOND:return H.TimestampSecond;case te.MILLISECOND:return H.TimestampMillisecond;case te.MICROSECOND:return H.TimestampMicrosecond;case te.NANOSECOND:return H.TimestampNanosecond}return H.Timestamp;case H.Date:switch(r.unit){case Bi.DAY:return H.DateDay;case Bi.MILLISECOND:return H.DateMillisecond}return H.Date;case H.Interval:switch(r.unit){case As.DAY_TIME:return H.IntervalDayTime;case As.YEAR_MONTH:return H.IntervalYearMonth}return H.Interval;case H.Duration:switch(r.unit){case te.SECOND:return H.DurationSecond;case te.MILLISECOND:return H.DurationMillisecond;case te.MICROSECOND:return H.DurationMicrosecond;case te.NANOSECOND:return H.DurationNanosecond}return H.Duration;case H.Map:return H.Map;case H.List:return H.List;case H.Struct:return H.Struct;case H.Union:switch(r.mode){case jn.Dense:return H.DenseUnion;case jn.Sparse:return H.SparseUnion}return H.Union;case H.FixedSizeBinary:return H.FixedSizeBinary;case H.FixedSizeList:return H.FixedSizeList;case H.Dictionary:return H.Dictionary}throw new Error(`Unrecognized type '${H[r.typeId]}'`)}he.prototype.visitInt8=null;he.prototype.visitInt16=null;he.prototype.visitInt32=null;he.prototype.visitInt64=null;he.prototype.visitUint8=null;he.prototype.visitUint16=null;he.prototype.visitUint32=null;he.prototype.visitUint64=null;he.prototype.visitFloat16=null;he.prototype.visitFloat32=null;he.prototype.visitFloat64=null;he.prototype.visitDateDay=null;he.prototype.visitDateMillisecond=null;he.prototype.visitTimestampSecond=null;he.prototype.visitTimestampMillisecond=null;he.prototype.visitTimestampMicrosecond=null;he.prototype.visitTimestampNanosecond=null;he.prototype.visitTimeSecond=null;he.prototype.visitTimeMillisecond=null;he.prototype.visitTimeMicrosecond=null;he.prototype.visitTimeNanosecond=null;he.prototype.visitDenseUnion=null;he.prototype.visitSparseUnion=null;he.prototype.visitIntervalDayTime=null;he.prototype.visitIntervalYearMonth=null;he.prototype.visitDuration=null;he.prototype.visitDurationSecond=null;he.prototype.visitDurationMillisecond=null;he.prototype.visitDurationMicrosecond=null;he.prototype.visitDurationNanosecond=null;const mS=new Float64Array(1),Hs=new Uint32Array(mS.buffer);function Tp(r){const t=(r&31744)>>10,e=(r&1023)/1024,n=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return n*(e?Number.NaN:1/0);case 0:return n*(e?6103515625e-14*e:0)}return n*Math.pow(2,t-15)*(1+e)}function gS(r){if(r!==r)return 32256;mS[0]=r;const t=(Hs[1]&2147483648)>>16&65535;let e=Hs[1]&2146435072,n=0;return e>=1089470464?Hs[0]>0?e=31744:(e=(e&2080374784)>>16,n=(Hs[1]&1048575)>>10):e<=1056964608?(n=1048576+(Hs[1]&1048575),n=1048576+(n<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,n=(Hs[1]&1048575)+512>>10),t|e|n&65535}const $L=Object.freeze(Object.defineProperty({__proto__:null,float64ToUint16:gS,uint16ToFloat64:Tp},Symbol.toStringTag,{value:"Module"}));class Wt extends he{}function qt(r){return(t,e,n)=>{if(t.setValid(e,n!=null))return r(t,e,n)}}const GL=(r,t,e)=>{r[t]=Math.floor(e/864e5)},yS=(r,t,e,n)=>{if(e+1{const i=r+e;n?t[i>>3]|=1<>3]&=~(1<{r[t]=e},Ip=({values:r},t,e)=>{r[t]=e},vS=({values:r},t,e)=>{r[t]=gS(e)},HL=(r,t,e)=>{switch(r.type.precision){case Dr.HALF:return vS(r,t,e);case Dr.SINGLE:case Dr.DOUBLE:return Ip(r,t,e)}},_S=({values:r},t,e)=>{GL(r,t,e.valueOf())},bS=({values:r},t,e)=>{r[t]=BigInt(e)},XL=({stride:r,values:t},e,n)=>{t.set(n.subarray(0,r),r*e)},wS=({values:r,valueOffsets:t},e,n)=>yS(r,t,e,n),xS=({values:r,valueOffsets:t},e,n)=>yS(r,t,e,zx(n)),YL=(r,t,e)=>{r.type.unit===Bi.DAY?_S(r,t,e):bS(r,t,e)},SS=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},TS=({values:r},t,e)=>{r[t]=BigInt(e)},IS=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},ES=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},qL=(r,t,e)=>{switch(r.type.unit){case te.SECOND:return SS(r,t,e);case te.MILLISECOND:return TS(r,t,e);case te.MICROSECOND:return IS(r,t,e);case te.NANOSECOND:return ES(r,t,e)}},AS=({values:r},t,e)=>{r[t]=e},MS=({values:r},t,e)=>{r[t]=e},CS=({values:r},t,e)=>{r[t]=e},OS=({values:r},t,e)=>{r[t]=e},QL=(r,t,e)=>{switch(r.type.unit){case te.SECOND:return AS(r,t,e);case te.MILLISECOND:return MS(r,t,e);case te.MICROSECOND:return CS(r,t,e);case te.NANOSECOND:return OS(r,t,e)}},ZL=({values:r,stride:t},e,n)=>{r.set(n.subarray(0,t),t*e)},KL=(r,t,e)=>{const n=r.children[0],i=r.valueOffsets,s=$n.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=i[t],l=i[t+1];a{const n=r.children[0],{valueOffsets:i}=r,s=$n.getVisitFn(n);let{[t]:o,[t+1]:a}=i;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(n,o,u),++o>=a)break},tN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t[s]),eN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t.get(s)),rN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t.get(i.name)),nN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t[i.name]),iN=(r,t,e)=>{const n=r.type.children.map(s=>$n.getVisitFn(s.type)),i=e instanceof Map?rN(t,e):e instanceof er?eN(t,e):Array.isArray(e)?tN(t,e):nN(t,e);r.type.children.forEach((s,o)=>i(n[o],r.children[o],s,o))},sN=(r,t,e)=>{r.type.mode===jn.Dense?PS(r,t,e):RS(r,t,e)},PS=(r,t,e)=>{const n=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[n];$n.visit(i,r.valueOffsets[t],e)},RS=(r,t,e)=>{const n=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[n];$n.visit(i,t,e)},oN=(r,t,e)=>{var n;(n=r.dictionary)===null||n===void 0||n.set(r.values[t],e)},aN=(r,t,e)=>{r.type.unit===As.DAY_TIME?FS(r,t,e):DS(r,t,e)},FS=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},DS=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},LS=({values:r},t,e)=>{r[t]=e},NS=({values:r},t,e)=>{r[t]=e},BS=({values:r},t,e)=>{r[t]=e},US=({values:r},t,e)=>{r[t]=e},lN=(r,t,e)=>{switch(r.type.unit){case te.SECOND:return LS(r,t,e);case te.MILLISECOND:return NS(r,t,e);case te.MICROSECOND:return BS(r,t,e);case te.NANOSECOND:return US(r,t,e)}},uN=(r,t,e)=>{const{stride:n}=r,i=r.children[0],s=$n.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=t*n;++o`${Fo(t)}: ${Fo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new cN(this[cn],this[To])}}class cN{constructor(t,e){this.childIndex=0,this.children=t.children,this.rowIndex=e,this.childFields=t.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const t=this.childIndex;return te.name)}has(t,e){return t[cn].type.children.some(n=>n.name===e)}getOwnPropertyDescriptor(t,e){if(t[cn].type.children.some(n=>n.name===e))return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const n=t[cn].type.children.findIndex(i=>i.name===e);if(n!==-1){const i=on.visit(t[cn].children[n],t[To]);return Reflect.set(t,e,i),i}}set(t,e,n){const i=t[cn].type.children.findIndex(s=>s.name===e);return i!==-1?($n.visit(t[cn].children[i],t[To],n),Reflect.set(t,e,n)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,n):!1}}const dN=new hN;class Bt extends he{}function Ht(r){return(t,e)=>t.getValid(e)?r(t,e):null}const fN=(r,t)=>864e5*r[t],pN=(r,t)=>null,kS=(r,t,e)=>{if(e+1>=t.length)return null;const n=pr(t[e]),i=pr(t[e+1]);return r.subarray(n,i)},mN=({offset:r,values:t},e)=>{const n=r+e;return(t[n>>3]&1<fN(r,t),VS=({values:r},t)=>pr(r[t]),Vi=({stride:r,values:t},e)=>t[r*e],gN=({stride:r,values:t},e)=>Tp(t[r*e]),jS=({values:r},t)=>r[t],yN=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),$S=({values:r,valueOffsets:t},e)=>kS(r,t,e),GS=({values:r,valueOffsets:t},e)=>{const n=kS(r,t,e);return n!==null?ZD(n):null},vN=({values:r},t)=>r[t],_N=({type:r,values:t},e)=>r.precision!==Dr.HALF?t[e]:Tp(t[e]),bN=(r,t)=>r.type.unit===Bi.DAY?zS(r,t):VS(r,t),WS=({values:r},t)=>1e3*pr(r[t]),HS=({values:r},t)=>pr(r[t]),XS=({values:r},t)=>$x(r[t],BigInt(1e3)),YS=({values:r},t)=>$x(r[t],BigInt(1e6)),wN=(r,t)=>{switch(r.type.unit){case te.SECOND:return WS(r,t);case te.MILLISECOND:return HS(r,t);case te.MICROSECOND:return XS(r,t);case te.NANOSECOND:return YS(r,t)}},qS=({values:r},t)=>r[t],QS=({values:r},t)=>r[t],ZS=({values:r},t)=>r[t],KS=({values:r},t)=>r[t],xN=(r,t)=>{switch(r.type.unit){case te.SECOND:return qS(r,t);case te.MILLISECOND:return QS(r,t);case te.MICROSECOND:return ZS(r,t);case te.NANOSECOND:return KS(r,t)}},SN=({values:r,stride:t},e)=>hc.decimal(r.subarray(t*e,t*(e+1))),TN=(r,t)=>{const{valueOffsets:e,stride:n,children:i}=r,{[t*n]:s,[t*n+1]:o}=e,l=i[0].slice(s,o-s);return new er([l])},IN=(r,t)=>{const{valueOffsets:e,children:n}=r,{[t]:i,[t+1]:s}=e,o=n[0];return new Ap(o.slice(i,s-i))},EN=(r,t)=>new Ep(r,t),AN=(r,t)=>r.type.mode===jn.Dense?JS(r,t):tT(r,t),JS=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[e];return on.visit(n,r.valueOffsets[t])},tT=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[e];return on.visit(n,t)},MN=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},CN=(r,t)=>r.type.unit===As.DAY_TIME?eT(r,t):rT(r,t),eT=({values:r},t)=>r.subarray(2*t,2*(t+1)),rT=({values:r},t)=>{const e=r[t],n=new Int32Array(2);return n[0]=Math.trunc(e/12),n[1]=Math.trunc(e%12),n},nT=({values:r},t)=>r[t],iT=({values:r},t)=>r[t],sT=({values:r},t)=>r[t],oT=({values:r},t)=>r[t],ON=(r,t)=>{switch(r.type.unit){case te.SECOND:return nT(r,t);case te.MILLISECOND:return iT(r,t);case te.MICROSECOND:return sT(r,t);case te.NANOSECOND:return oT(r,t)}},PN=(r,t)=>{const{stride:e,children:n}=r,s=n[0].slice(t*e,e);return new er([s])};Bt.prototype.visitNull=Ht(pN);Bt.prototype.visitBool=Ht(mN);Bt.prototype.visitInt=Ht(vN);Bt.prototype.visitInt8=Ht(Vi);Bt.prototype.visitInt16=Ht(Vi);Bt.prototype.visitInt32=Ht(Vi);Bt.prototype.visitInt64=Ht(jS);Bt.prototype.visitUint8=Ht(Vi);Bt.prototype.visitUint16=Ht(Vi);Bt.prototype.visitUint32=Ht(Vi);Bt.prototype.visitUint64=Ht(jS);Bt.prototype.visitFloat=Ht(_N);Bt.prototype.visitFloat16=Ht(gN);Bt.prototype.visitFloat32=Ht(Vi);Bt.prototype.visitFloat64=Ht(Vi);Bt.prototype.visitUtf8=Ht(GS);Bt.prototype.visitLargeUtf8=Ht(GS);Bt.prototype.visitBinary=Ht($S);Bt.prototype.visitLargeBinary=Ht($S);Bt.prototype.visitFixedSizeBinary=Ht(yN);Bt.prototype.visitDate=Ht(bN);Bt.prototype.visitDateDay=Ht(zS);Bt.prototype.visitDateMillisecond=Ht(VS);Bt.prototype.visitTimestamp=Ht(wN);Bt.prototype.visitTimestampSecond=Ht(WS);Bt.prototype.visitTimestampMillisecond=Ht(HS);Bt.prototype.visitTimestampMicrosecond=Ht(XS);Bt.prototype.visitTimestampNanosecond=Ht(YS);Bt.prototype.visitTime=Ht(xN);Bt.prototype.visitTimeSecond=Ht(qS);Bt.prototype.visitTimeMillisecond=Ht(QS);Bt.prototype.visitTimeMicrosecond=Ht(ZS);Bt.prototype.visitTimeNanosecond=Ht(KS);Bt.prototype.visitDecimal=Ht(SN);Bt.prototype.visitList=Ht(TN);Bt.prototype.visitStruct=Ht(EN);Bt.prototype.visitUnion=Ht(AN);Bt.prototype.visitDenseUnion=Ht(JS);Bt.prototype.visitSparseUnion=Ht(tT);Bt.prototype.visitDictionary=Ht(MN);Bt.prototype.visitInterval=Ht(CN);Bt.prototype.visitIntervalDayTime=Ht(eT);Bt.prototype.visitIntervalYearMonth=Ht(rT);Bt.prototype.visitDuration=Ht(ON);Bt.prototype.visitDurationSecond=Ht(nT);Bt.prototype.visitDurationMillisecond=Ht(iT);Bt.prototype.visitDurationMicrosecond=Ht(sT);Bt.prototype.visitDurationNanosecond=Ht(oT);Bt.prototype.visitFixedSizeList=Ht(PN);Bt.prototype.visitMap=Ht(IN);const on=new Bt,lo=Symbol.for("keys"),Io=Symbol.for("vals"),uo=Symbol.for("kKeysAsStrings"),df=Symbol.for("_kKeysAsStrings");class Ap{constructor(t){return this[lo]=new er([t.children[0]]).memoize(),this[Io]=t.children[1],new Proxy(this,new FN)}get[uo](){return this[df]||(this[df]=Array.from(this[lo].toArray(),String))}[Symbol.iterator](){return new RN(this[lo],this[Io])}get size(){return this[lo].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[lo],e=this[Io],n={};for(let i=-1,s=t.length;++i`${Fo(t)}: ${Fo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class RN{constructor(t,e){this.keys=t,this.vals=e,this.keyIndex=0,this.numKeys=t.length}[Symbol.iterator](){return this}next(){const t=this.keyIndex;return t===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(t),on.visit(this.vals,t)]})}}class FN{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[uo]}has(t,e){return t[uo].includes(e)}getOwnPropertyDescriptor(t,e){if(t[uo].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const n=t[uo].indexOf(e);if(n!==-1){const i=on.visit(Reflect.get(t,Io),n);return Reflect.set(t,e,i),i}}set(t,e,n){const i=t[uo].indexOf(e);return i!==-1?($n.visit(Reflect.get(t,Io),i,n),Reflect.set(t,e,n)):Reflect.has(t,e)?Reflect.set(t,e,n):!1}}Object.defineProperties(Ap.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[lo]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Io]:{writable:!0,enumerable:!1,configurable:!1,value:null},[df]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let qy;function aT(r,t,e,n){const{length:i=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?i:e;return s<0&&(s=(s%i+i)%i),o<0&&(o=(o%i+i)%i),oi&&(o=i),n?n(r,s,o):[s,o]}const lT=(r,t)=>r<0?t+r:r,Qy=r=>r!==r;function Ds(r){if(typeof r!=="object"||r===null)return Qy(r)?Qy:e=>e===r;if(r instanceof Date){const e=r.valueOf();return n=>n instanceof Date?n.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?jx(r,e):!1:r instanceof Map?LN(r):Array.isArray(r)?DN(r):r instanceof er?NN(r):BN(r,!0)}function DN(r){const t=[];for(let e=-1,n=r.length;++e!1;const n=[];for(let i=-1,s=e.length;++i{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return UN(r,e);case Map:return Zy(r,e,e.keys());case Ap:case Ep:case Object:case void 0:return Zy(r,e,t||Object.keys(e))}return e instanceof er?kN(r,e):!1}}function UN(r,t){const e=r.length;if(t.length!==e)return!1;for(let n=-1;++n>n}function VN(r,t,e){return e?!!(r[t>>3]|=1<>3]&=~(1<0||e.byteLength>3):cT(new fc(e,r,t,null,Mp)).subarray(0,n)),i}return e}function cT(r){const t=[];let e=0,n=0,i=0;for(const o of r)o&&(i|=1<0)&&(t[e++]=i);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}class fc{constructor(t,e,n,i,s){this.bytes=t,this.length=n,this.context=i,this.get=s,this.bit=e%8,this.byteIndex=e>>3,this.byte=t[this.byteIndex++],this.index=0}next(){return this.index>3<<3,i=t+(t%8===0?0:8-t%8);return ju(r,t,i)+ju(r,n,e)+hT(r,i>>3,n-i>>3)}function hT(r,t,e){let n=0,i=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:i+e;for(;o-i>=4;)n+=Zl(s.getUint32(i)),i+=4;for(;o-i>=2;)n+=Zl(s.getUint16(i)),i+=2;for(;o-i>=1;)n+=Zl(s.getUint8(i)),i+=1;return n}function Zl(r){let t=Math.trunc(r);return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}const jN=Object.freeze(Object.defineProperty({__proto__:null,BitIterator:fc,getBit:uT,getBool:Mp,packBools:cT,popcnt_array:hT,popcnt_bit_range:ju,popcnt_uint32:Zl,setBool:VN,truncateBitmap:ff},Symbol.toStringTag,{value:"Module"})),$N=-1;class Ga{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:t}=this;return Ct.isSparseUnion(t)?this.children.some(e=>e.nullable):Ct.isDenseUnion(t)?this.children.some(e=>e.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let t=0;const{valueOffsets:e,values:n,nullBitmap:i,typeIds:s}=this;return e&&(t+=e.byteLength),n&&(t+=n.byteLength),i&&(t+=i.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(Ct.isUnion(this.type))return this.children.reduce((n,i)=>n+i.nullCount,0);let t=this._nullCount,e;return t<=$N&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-ju(e,this.offset,this.offset+this.length)),t}constructor(t,e,n,i,s,o=[],a){this.type=t,this.children=o,this.dictionary=a,this.offset=Math.floor(Math.max(e||0,0)),this.length=Math.floor(Math.max(n||0,0)),this._nullCount=Math.floor(Math.max(i||0,-1));let l;s instanceof Ga?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=pS(t),s&&((l=s[0])&&(this.valueOffsets=l),(l=s[1])&&(this.values=l),(l=s[2])&&(this.nullBitmap=l),(l=s[3])&&(this.typeIds=l)))}getValid(t){const{type:e}=this;if(Ct.isUnion(e)){const n=e,i=this.children[n.typeIdToChildIndex[this.typeIds[t]]],s=n.mode===jn.Dense?this.valueOffsets[t]:t;return i.getValid(s)}if(this.nullable&&this.nullCount>0){const n=this.offset+t;return(this.nullBitmap[n>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(ff(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];n=(h&u)!==0,s[c]=e?h|u:h&~u}return n!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,n=this.length,i=this._nullCount,s=this,o=this.children){return new Ga(t,e,n,i,s,o,this.dictionary)}slice(t,e){const{stride:n,typeId:i,children:s}=this,o=+(this._nullCount===0)-1,a=i===16?n:1,l=this._sliceBuffers(t,e,n,i);return this.clone(this.type,this.offset+t,e,o,l,s.length===0||this.valueOffsets?s:this._sliceChildren(s,a*t,a*e))}_changeLengthAndBackfillNullBitmap(t){if(this.typeId===H.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:n}=this,i=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);i[e>>3]=(1<0&&i.set(ff(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[si.VALIDITY]=i,this.clone(this.type,0,t,n+(t-e),s)}_sliceBuffers(t,e,n,i){let s;const{buffers:o}=this;return(s=o[si.TYPE])&&(o[si.TYPE]=s.subarray(t,t+e)),(s=o[si.OFFSET])&&(o[si.OFFSET]=s.subarray(t,t+e+1))||(s=o[si.DATA])&&(o[si.DATA]=i===6?s:s.subarray(n*t,n*(t+e))),o}_sliceChildren(t,e,n){return t.map(i=>i.slice(e,n))}}Ga.prototype.children=Object.freeze([]);class Ky{constructor(t=0,e){this.numChunks=t,this.getChunkIterator=e,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndext.nullable)}function WN(r){return r.reduce((t,e)=>t+e.nullCount,0)}function HN(r){return r.reduce((t,e,n)=>(t[n+1]=t[n]+e.length,t),new Uint32Array(r.length+1))}function XN(r,t,e,n){const i=[];for(let s=-1,o=r.length;++s=n)break;if(e>=l+u)continue;if(l>=e&&l+u<=n){i.push(a);continue}const c=Math.max(0,e-l),h=Math.min(n-l,u);i.push(a.slice(c,h-c))}return i.length===0&&i.push(r[0].slice(0,0)),i}function Cp(r,t,e,n){let i=0,s=0,o=t.length-1;do{if(i>=o-1)return e0?0:-1}function ZN(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let n=0;for(const i of new fc(e,r.offset+(t||0),r.length,e,Mp)){if(!i)return n;++n}return-1}function Kt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case H.Union:break;case H.Dictionary:break;default:return ZN(r,e)}const n=on.getVisitFn(r),i=Ds(t);for(let s=(e||0)-1,o=r.length;++s{const i=r.data[n];return i.values.subarray(0,i.length)[Symbol.iterator]()});let e=0;return new Ky(r.data.length,n=>{const s=r.data[n].length,o=r.slice(e,e+s);return e+=s,new KN(o)})}class KN{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof Ga)))throw new TypeError("Vector constructor expects an Array of Data instances.");const o=(e=s[0])===null||e===void 0?void 0:e.type;switch(s.length){case 0:this._offsets=[0];break;case 1:{const{get:a,set:l,indexOf:u}=mT[o.typeId],c=s[0];this.isValid=h=>dT(c,h),this.get=h=>a(c,h),this.set=(h,f)=>l(c,h,f),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,gT[o.typeId]),this._offsets=HN(s);break}this.data=s,this.type=o,this.stride=pS(o),this.numChildren=(i=(n=o.children)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return GN(this.data)}get nullCount(){return WN(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${H[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(lT(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return JN.visit(this)}concat(...t){return new er(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new er(aT(this,t,e,({data:n,_offsets:i},s,o)=>XN(n,i,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:n,stride:i,ArrayType:s}=this;switch(t.typeId){case H.Int:case H.Float:case H.Decimal:case H.Time:case H.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,n*i);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*i),o.offset),o.offset+=l*i,o),{array:new s(n*i),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(t){var e;return this.getChildAt((e=this.type.children)===null||e===void 0?void 0:e.findIndex(n=>n.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return Ct.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(Ct.isDictionary(this.type)){const t=new $u(this.data[0].dictionary),e=this.data.map(n=>{const i=n.clone();return i.dictionary=t,i});return new er(e)}return new $u(this)}unmemoize(){if(Ct.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(n=>{const i=n.clone();return i.dictionary=t,i});return new er(e)}return this}}pT=Symbol.toStringTag;er[pT]=(r=>{r.type=Ct.prototype,r.data=[],r.length=0,r.stride=1,r.numChildren=0,r._offsets=new Uint32Array([0]),r[Symbol.isConcatSpreadable]=!0;const t=Object.keys(H).map(e=>H[e]).filter(e=>typeof e=="number"&&e!==H.NONE);for(const e of t){const n=on.getVisitFnByTypeId(e),i=$n.getVisitFnByTypeId(e),s=tv.getVisitFnByTypeId(e);mT[e]={get:n,set:i,indexOf:s},gT[e]=Object.create(r,{isValid:{value:Jy(dT)},get:{value:Jy(on.getVisitFnByTypeId(e))},set:{value:YN($n.getVisitFnByTypeId(e))},indexOf:{value:qN(tv.getVisitFnByTypeId(e))}})}return"Vector"})(er.prototype);class $u extends er{constructor(t){super(t.data);const e=this.get,n=this.set,i=this.slice,s=new Array(this.length);Object.defineProperty(this,"get",{value(o){const a=s[o];if(a!==void 0)return a;const l=e.call(this,o);return s[o]=l,l}}),Object.defineProperty(this,"set",{value(o,a){n.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new $u(i.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new er(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}const tB=65536;function po(r){return r<0&&(r=4294967295+r+1),`0x${r.toString(16)}`}const Lo=8,Op=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8];class Pp{constructor(t){this.buffer=t}high(){return this.buffer[1]}low(){return this.buffer[0]}_times(t){const e=new Uint32Array([this.buffer[1]>>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),n=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let i=e[3]*n[3];this.buffer[0]=i&65535;let s=i>>>16;return i=e[2]*n[3],s+=i,i=e[3]*n[2]>>>0,s+=i,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*n[3]+e[2]*n[2]+e[3]*n[1],this.buffer[1]+=e[0]*n[3]+e[1]*n[2]+e[2]*n[1]+e[3]*n[0]<<16,this}_plus(t){const e=this.buffer[0]+t.buffer[0]>>>0;this.buffer[1]+=t.buffer[1],e>>0&&++this.buffer[1],this.buffer[0]=e}lessThan(t){return this.buffer[1]>>0,e[2]=this.buffer[2]+t.buffer[2]>>>0,e[1]=this.buffer[1]+t.buffer[1]>>>0,e[0]=this.buffer[0]+t.buffer[0]>>>0,e[0]>>0&&++e[1],e[1]>>0&&++e[2],e[2]>>0&&++e[3],this.buffer[3]=e[3],this.buffer[2]=e[2],this.buffer[1]=e[1],this.buffer[0]=e[0],this}hex(){return`${po(this.buffer[3])} ${po(this.buffer[2])} ${po(this.buffer[1])} ${po(this.buffer[0])}`}static multiply(t,e){return new En(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new En(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return En.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return En.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const n=t.startsWith("-"),i=t.length,s=new En(e);for(let o=n?1:0;othis.compareFields(n,e[i]))}compareFields(t,e){return t===e||e instanceof t.constructor&&t.name===e.name&&t.nullable===e.nullable&&this.visit(t.type,e.type)}}function gr(r,t){return t instanceof r.constructor}function Ls(r,t){return r===t||gr(r,t)}function mi(r,t){return r===t||gr(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function pc(r,t){return r===t||gr(r,t)&&r.precision===t.precision}function rB(r,t){return r===t||gr(r,t)&&r.byteWidth===t.byteWidth}function Rp(r,t){return r===t||gr(r,t)&&r.unit===t.unit}function rl(r,t){return r===t||gr(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function nl(r,t){return r===t||gr(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function nB(r,t){return r===t||gr(r,t)&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}function iB(r,t){return r===t||gr(r,t)&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}function Fp(r,t){return r===t||gr(r,t)&&r.mode===t.mode&&r.typeIds.every((e,n)=>e===t.typeIds[n])&&Gn.compareManyFields(r.children,t.children)}function sB(r,t){return r===t||gr(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&Gn.visit(r.indices,t.indices)&&Gn.visit(r.dictionary,t.dictionary)}function Dp(r,t){return r===t||gr(r,t)&&r.unit===t.unit}function il(r,t){return r===t||gr(r,t)&&r.unit===t.unit}function oB(r,t){return r===t||gr(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}function aB(r,t){return r===t||gr(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}zt.prototype.visitNull=Ls;zt.prototype.visitBool=Ls;zt.prototype.visitInt=mi;zt.prototype.visitInt8=mi;zt.prototype.visitInt16=mi;zt.prototype.visitInt32=mi;zt.prototype.visitInt64=mi;zt.prototype.visitUint8=mi;zt.prototype.visitUint16=mi;zt.prototype.visitUint32=mi;zt.prototype.visitUint64=mi;zt.prototype.visitFloat=pc;zt.prototype.visitFloat16=pc;zt.prototype.visitFloat32=pc;zt.prototype.visitFloat64=pc;zt.prototype.visitUtf8=Ls;zt.prototype.visitLargeUtf8=Ls;zt.prototype.visitBinary=Ls;zt.prototype.visitLargeBinary=Ls;zt.prototype.visitFixedSizeBinary=rB;zt.prototype.visitDate=Rp;zt.prototype.visitDateDay=Rp;zt.prototype.visitDateMillisecond=Rp;zt.prototype.visitTimestamp=rl;zt.prototype.visitTimestampSecond=rl;zt.prototype.visitTimestampMillisecond=rl;zt.prototype.visitTimestampMicrosecond=rl;zt.prototype.visitTimestampNanosecond=rl;zt.prototype.visitTime=nl;zt.prototype.visitTimeSecond=nl;zt.prototype.visitTimeMillisecond=nl;zt.prototype.visitTimeMicrosecond=nl;zt.prototype.visitTimeNanosecond=nl;zt.prototype.visitDecimal=Ls;zt.prototype.visitList=nB;zt.prototype.visitStruct=iB;zt.prototype.visitUnion=Fp;zt.prototype.visitDenseUnion=Fp;zt.prototype.visitSparseUnion=Fp;zt.prototype.visitDictionary=sB;zt.prototype.visitInterval=Dp;zt.prototype.visitIntervalDayTime=Dp;zt.prototype.visitIntervalYearMonth=Dp;zt.prototype.visitDuration=il;zt.prototype.visitDurationSecond=il;zt.prototype.visitDurationMillisecond=il;zt.prototype.visitDurationMicrosecond=il;zt.prototype.visitDurationNanosecond=il;zt.prototype.visitFixedSizeList=oB;zt.prototype.visitMap=aB;const Gn=new zt;function lB(r,t){return Gn.compareSchemas(r,t)}function uB(r,t){return Gn.compareFields(r,t)}function cB(r,t){return Gn.visit(r,t)}const ev=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zL),eB),jN),$L),LL),zN),BL),{compareSchemas:lB,compareFields:uB,compareTypes:cB}),yT=6048e5,hB=864e5,rv=Symbol.for("constructDateFrom");function ui(r,t){return typeof r=="function"?r(t):r&&typeof r=="object"&&rv in r?r[rv](t):r instanceof Date?new r.constructor(t):new Date(t)}function an(r,t){return ui(t||r,r)}let dB={};function mc(){return dB}function Wa(r,t){var a,l,u,c;const e=mc(),n=(t==null?void 0:t.weekStartsOn)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.weekStartsOn)??e.weekStartsOn??((c=(u=e.locale)==null?void 0:u.options)==null?void 0:c.weekStartsOn)??0,i=an(r,t==null?void 0:t.in),s=i.getDay(),o=(s=s.getTime()?n+1:e.getTime()>=a.getTime()?n:n-1}function nv(r){const t=an(r),e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),+r-+e}function fB(r,...t){const e=ui.bind(null,t.find(n=>typeof n=="object"));return t.map(e)}function iv(r,t){const e=an(r,t==null?void 0:t.in);return e.setHours(0,0,0,0),e}function pB(r,t,e){const[n,i]=fB(e==null?void 0:e.in,r,t),s=iv(n),o=iv(i),a=+s-nv(s),l=+o-nv(o);return Math.round((a-l)/hB)}function mB(r,t){const e=vT(r,t),n=ui(r,0);return n.setFullYear(e,0,4),n.setHours(0,0,0,0),Gu(n)}function gB(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function yB(r){return!(!gB(r)&&typeof r!="number"||isNaN(+an(r)))}function vB(r,t){const e=an(r,t==null?void 0:t.in);return e.setFullYear(e.getFullYear(),0,1),e.setHours(0,0,0,0),e}const _B={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},bB=(r,t,e)=>{let n;const i=_B[r];return typeof i=="string"?n=i:t===1?n=i.one:n=i.other.replace("{{count}}",t.toString()),e!=null&&e.addSuffix?e.comparison&&e.comparison>0?"in "+n:n+" ago":n};function zh(r){return(t={})=>{const e=t.width?String(t.width):r.defaultWidth;return r.formats[e]||r.formats[r.defaultWidth]}}const wB={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},xB={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},SB={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},TB={date:zh({formats:wB,defaultWidth:"full"}),time:zh({formats:xB,defaultWidth:"full"}),dateTime:zh({formats:SB,defaultWidth:"full"})},IB={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},EB=(r,t,e,n)=>IB[r];function sa(r){return(t,e)=>{const n=e!=null&&e.context?String(e.context):"standalone";let i;if(n==="formatting"&&r.formattingValues){const o=r.defaultFormattingWidth||r.defaultWidth,a=e!=null&&e.width?String(e.width):o;i=r.formattingValues[a]||r.formattingValues[o]}else{const o=r.defaultWidth,a=e!=null&&e.width?String(e.width):r.defaultWidth;i=r.values[a]||r.values[o]}const s=r.argumentCallback?r.argumentCallback(t):t;return i[s]}}const AB={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},MB={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},CB={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},OB={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},PB={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},RB={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},FB=(r,t)=>{const e=Number(r),n=e%100;if(n>20||n<10)switch(n%10){case 1:return e+"st";case 2:return e+"nd";case 3:return e+"rd"}return e+"th"},DB={ordinalNumber:FB,era:sa({values:AB,defaultWidth:"wide"}),quarter:sa({values:MB,defaultWidth:"wide",argumentCallback:r=>r-1}),month:sa({values:CB,defaultWidth:"wide"}),day:sa({values:OB,defaultWidth:"wide"}),dayPeriod:sa({values:PB,defaultWidth:"wide",formattingValues:RB,defaultFormattingWidth:"wide"})};function oa(r){return(t,e={})=>{const n=e.width,i=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],s=t.match(i);if(!s)return null;const o=s[0],a=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],l=Array.isArray(a)?NB(a,h=>h.test(o)):LB(a,h=>h.test(o));let u;u=r.valueCallback?r.valueCallback(l):l,u=e.valueCallback?e.valueCallback(u):u;const c=t.slice(o.length);return{value:u,rest:c}}}function LB(r,t){for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)&&t(r[e]))return e}function NB(r,t){for(let e=0;e{const n=t.match(r.matchPattern);if(!n)return null;const i=n[0],s=t.match(r.parsePattern);if(!s)return null;let o=r.valueCallback?r.valueCallback(s[0]):s[0];o=e.valueCallback?e.valueCallback(o):o;const a=t.slice(i.length);return{value:o,rest:a}}}const UB=/^(\d+)(th|st|nd|rd)?/i,kB=/\d+/i,zB={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},VB={any:[/^b/i,/^(a|c)/i]},jB={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},$B={any:[/1/i,/2/i,/3/i,/4/i]},GB={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},WB={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},HB={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},XB={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},YB={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},qB={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},QB={ordinalNumber:BB({matchPattern:UB,parsePattern:kB,valueCallback:r=>parseInt(r,10)}),era:oa({matchPatterns:zB,defaultMatchWidth:"wide",parsePatterns:VB,defaultParseWidth:"any"}),quarter:oa({matchPatterns:jB,defaultMatchWidth:"wide",parsePatterns:$B,defaultParseWidth:"any",valueCallback:r=>r+1}),month:oa({matchPatterns:GB,defaultMatchWidth:"wide",parsePatterns:WB,defaultParseWidth:"any"}),day:oa({matchPatterns:HB,defaultMatchWidth:"wide",parsePatterns:XB,defaultParseWidth:"any"}),dayPeriod:oa({matchPatterns:YB,defaultMatchWidth:"any",parsePatterns:qB,defaultParseWidth:"any"})},ZB={code:"en-US",formatDistance:bB,formatLong:TB,formatRelative:EB,localize:DB,match:QB,options:{weekStartsOn:0,firstWeekContainsDate:1}};function KB(r,t){const e=an(r,t==null?void 0:t.in);return pB(e,vB(e))+1}function JB(r,t){const e=an(r,t==null?void 0:t.in),n=+Gu(e)-+mB(e);return Math.round(n/yT)+1}function _T(r,t){var c,h,f,d;const e=an(r,t==null?void 0:t.in),n=e.getFullYear(),i=mc(),s=(t==null?void 0:t.firstWeekContainsDate)??((h=(c=t==null?void 0:t.locale)==null?void 0:c.options)==null?void 0:h.firstWeekContainsDate)??i.firstWeekContainsDate??((d=(f=i.locale)==null?void 0:f.options)==null?void 0:d.firstWeekContainsDate)??1,o=ui((t==null?void 0:t.in)||r,0);o.setFullYear(n+1,0,s),o.setHours(0,0,0,0);const a=Wa(o,t),l=ui((t==null?void 0:t.in)||r,0);l.setFullYear(n,0,s),l.setHours(0,0,0,0);const u=Wa(l,t);return+e>=+a?n+1:+e>=+u?n:n-1}function tU(r,t){var a,l,u,c;const e=mc(),n=(t==null?void 0:t.firstWeekContainsDate)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.firstWeekContainsDate)??e.firstWeekContainsDate??((c=(u=e.locale)==null?void 0:u.options)==null?void 0:c.firstWeekContainsDate)??1,i=_T(r,t),s=ui((t==null?void 0:t.in)||r,0);return s.setFullYear(i,0,n),s.setHours(0,0,0,0),Wa(s,t)}function eU(r,t){const e=an(r,t==null?void 0:t.in),n=+Wa(e,t)-+tU(e,t);return Math.round(n/yT)+1}function we(r,t){const e=r<0?"-":"",n=Math.abs(r).toString().padStart(t,"0");return e+n}const wi={y(r,t){const e=r.getFullYear(),n=e>0?e:1-e;return we(t==="yy"?n%100:n,t.length)},M(r,t){const e=r.getMonth();return t==="M"?String(e+1):we(e+1,2)},d(r,t){return we(r.getDate(),t.length)},a(r,t){const e=r.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return e.toUpperCase();case"aaa":return e;case"aaaaa":return e[0];case"aaaa":default:return e==="am"?"a.m.":"p.m."}},h(r,t){return we(r.getHours()%12||12,t.length)},H(r,t){return we(r.getHours(),t.length)},m(r,t){return we(r.getMinutes(),t.length)},s(r,t){return we(r.getSeconds(),t.length)},S(r,t){const e=t.length,n=r.getMilliseconds(),i=Math.trunc(n*Math.pow(10,e-3));return we(i,t.length)}},Xs={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},sv={G:function(r,t,e){const n=r.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return e.era(n,{width:"abbreviated"});case"GGGGG":return e.era(n,{width:"narrow"});case"GGGG":default:return e.era(n,{width:"wide"})}},y:function(r,t,e){if(t==="yo"){const n=r.getFullYear(),i=n>0?n:1-n;return e.ordinalNumber(i,{unit:"year"})}return wi.y(r,t)},Y:function(r,t,e,n){const i=_T(r,n),s=i>0?i:1-i;if(t==="YY"){const o=s%100;return we(o,2)}return t==="Yo"?e.ordinalNumber(s,{unit:"year"}):we(s,t.length)},R:function(r,t){const e=vT(r);return we(e,t.length)},u:function(r,t){const e=r.getFullYear();return we(e,t.length)},Q:function(r,t,e){const n=Math.ceil((r.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return we(n,2);case"Qo":return e.ordinalNumber(n,{unit:"quarter"});case"QQQ":return e.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return e.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return e.quarter(n,{width:"wide",context:"formatting"})}},q:function(r,t,e){const n=Math.ceil((r.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return we(n,2);case"qo":return e.ordinalNumber(n,{unit:"quarter"});case"qqq":return e.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return e.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return e.quarter(n,{width:"wide",context:"standalone"})}},M:function(r,t,e){const n=r.getMonth();switch(t){case"M":case"MM":return wi.M(r,t);case"Mo":return e.ordinalNumber(n+1,{unit:"month"});case"MMM":return e.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return e.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return e.month(n,{width:"wide",context:"formatting"})}},L:function(r,t,e){const n=r.getMonth();switch(t){case"L":return String(n+1);case"LL":return we(n+1,2);case"Lo":return e.ordinalNumber(n+1,{unit:"month"});case"LLL":return e.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return e.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return e.month(n,{width:"wide",context:"standalone"})}},w:function(r,t,e,n){const i=eU(r,n);return t==="wo"?e.ordinalNumber(i,{unit:"week"}):we(i,t.length)},I:function(r,t,e){const n=JB(r);return t==="Io"?e.ordinalNumber(n,{unit:"week"}):we(n,t.length)},d:function(r,t,e){return t==="do"?e.ordinalNumber(r.getDate(),{unit:"date"}):wi.d(r,t)},D:function(r,t,e){const n=KB(r);return t==="Do"?e.ordinalNumber(n,{unit:"dayOfYear"}):we(n,t.length)},E:function(r,t,e){const n=r.getDay();switch(t){case"E":case"EE":case"EEE":return e.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return e.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return e.day(n,{width:"short",context:"formatting"});case"EEEE":default:return e.day(n,{width:"wide",context:"formatting"})}},e:function(r,t,e,n){const i=r.getDay(),s=(i-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(s);case"ee":return we(s,2);case"eo":return e.ordinalNumber(s,{unit:"day"});case"eee":return e.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return e.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return e.day(i,{width:"short",context:"formatting"});case"eeee":default:return e.day(i,{width:"wide",context:"formatting"})}},c:function(r,t,e,n){const i=r.getDay(),s=(i-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(s);case"cc":return we(s,t.length);case"co":return e.ordinalNumber(s,{unit:"day"});case"ccc":return e.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return e.day(i,{width:"narrow",context:"standalone"});case"cccccc":return e.day(i,{width:"short",context:"standalone"});case"cccc":default:return e.day(i,{width:"wide",context:"standalone"})}},i:function(r,t,e){const n=r.getDay(),i=n===0?7:n;switch(t){case"i":return String(i);case"ii":return we(i,t.length);case"io":return e.ordinalNumber(i,{unit:"day"});case"iii":return e.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return e.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return e.day(n,{width:"short",context:"formatting"});case"iiii":default:return e.day(n,{width:"wide",context:"formatting"})}},a:function(r,t,e){const i=r.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return e.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return e.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(r,t,e){const n=r.getHours();let i;switch(n===12?i=Xs.noon:n===0?i=Xs.midnight:i=n/12>=1?"pm":"am",t){case"b":case"bb":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return e.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return e.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(r,t,e){const n=r.getHours();let i;switch(n>=17?i=Xs.evening:n>=12?i=Xs.afternoon:n>=4?i=Xs.morning:i=Xs.night,t){case"B":case"BB":case"BBB":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return e.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return e.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(r,t,e){if(t==="ho"){let n=r.getHours()%12;return n===0&&(n=12),e.ordinalNumber(n,{unit:"hour"})}return wi.h(r,t)},H:function(r,t,e){return t==="Ho"?e.ordinalNumber(r.getHours(),{unit:"hour"}):wi.H(r,t)},K:function(r,t,e){const n=r.getHours()%12;return t==="Ko"?e.ordinalNumber(n,{unit:"hour"}):we(n,t.length)},k:function(r,t,e){let n=r.getHours();return n===0&&(n=24),t==="ko"?e.ordinalNumber(n,{unit:"hour"}):we(n,t.length)},m:function(r,t,e){return t==="mo"?e.ordinalNumber(r.getMinutes(),{unit:"minute"}):wi.m(r,t)},s:function(r,t,e){return t==="so"?e.ordinalNumber(r.getSeconds(),{unit:"second"}):wi.s(r,t)},S:function(r,t){return wi.S(r,t)},X:function(r,t,e){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return av(n);case"XXXX":case"XX":return hs(n);case"XXXXX":case"XXX":default:return hs(n,":")}},x:function(r,t,e){const n=r.getTimezoneOffset();switch(t){case"x":return av(n);case"xxxx":case"xx":return hs(n);case"xxxxx":case"xxx":default:return hs(n,":")}},O:function(r,t,e){const n=r.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+ov(n,":");case"OOOO":default:return"GMT"+hs(n,":")}},z:function(r,t,e){const n=r.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+ov(n,":");case"zzzz":default:return"GMT"+hs(n,":")}},t:function(r,t,e){const n=Math.trunc(+r/1e3);return we(n,t.length)},T:function(r,t,e){return we(+r,t.length)}};function ov(r,t=""){const e=r>0?"-":"+",n=Math.abs(r),i=Math.trunc(n/60),s=n%60;return s===0?e+String(i):e+String(i)+t+we(s,2)}function av(r,t){return r%60===0?(r>0?"-":"+")+we(Math.abs(r)/60,2):hs(r,t)}function hs(r,t=""){const e=r>0?"-":"+",n=Math.abs(r),i=we(Math.trunc(n/60),2),s=we(n%60,2);return e+i+t+s}const lv=(r,t)=>{switch(r){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},bT=(r,t)=>{switch(r){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},rU=(r,t)=>{const e=r.match(/(P+)(p+)?/)||[],n=e[1],i=e[2];if(!i)return lv(r,t);let s;switch(n){case"P":s=t.dateTime({width:"short"});break;case"PP":s=t.dateTime({width:"medium"});break;case"PPP":s=t.dateTime({width:"long"});break;case"PPPP":default:s=t.dateTime({width:"full"});break}return s.replace("{{date}}",lv(n,t)).replace("{{time}}",bT(i,t))},nU={p:bT,P:rU},iU=/^D+$/,sU=/^Y+$/,oU=["D","DD","YY","YYYY"];function aU(r){return iU.test(r)}function lU(r){return sU.test(r)}function uU(r,t,e){const n=cU(r,t,e);if(console.warn(n),oU.includes(r))throw new RangeError(n)}function cU(r,t,e){const n=r[0]==="Y"?"years":"days of the month";return`Use \`${r.toLowerCase()}\` instead of \`${r}\` (in \`${t}\`) for formatting ${n} to the input \`${e}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const hU=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,dU=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,fU=/^'([^]*?)'?$/,pU=/''/g,mU=/[a-zA-Z]/;function wT(r,t,e){var c,h,f,d;const n=mc(),i=n.locale??ZB,s=n.firstWeekContainsDate??((h=(c=n.locale)==null?void 0:c.options)==null?void 0:h.firstWeekContainsDate)??1,o=n.weekStartsOn??((d=(f=n.locale)==null?void 0:f.options)==null?void 0:d.weekStartsOn)??0,a=an(r,e==null?void 0:e.in);if(!yB(a))throw new RangeError("Invalid time value");let l=t.match(dU).map(m=>{const g=m[0];if(g==="p"||g==="P"){const p=nU[g];return p(m,i.formatLong)}return m}).join("").match(hU).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const g=m[0];if(g==="'")return{isToken:!1,value:gU(m)};if(sv[g])return{isToken:!0,value:m};if(g.match(mU))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:m}});i.localize.preprocessor&&(l=i.localize.preprocessor(a,l));const u={firstWeekContainsDate:s,weekStartsOn:o,locale:i};return l.map(m=>{if(!m.isToken)return m.value;const g=m.value;(lU(g)||aU(g))&&uU(g,t,String(r));const p=sv[g[0]];return p(a,g,i.localize,u)}).join("")}function gU(r){const t=r.match(fU);return t?t[1].replace(pU,"'"):r}function yU(r,t){return an(r*1e3,t==null?void 0:t.in)}function vU(r,t){const e=_U(t)?new t(0):ui(t,0);return e.setFullYear(r.getFullYear(),r.getMonth(),r.getDate()),e.setHours(r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()),e}function _U(r){var t;return typeof r=="function"&&((t=r.prototype)==null?void 0:t.constructor)===r}function bU(r,t){let e=r.length;switch("string"){case"string":{for(;e>0&&r[e-1]===t;)e--;break}}return r.substring(0,e)}function Tr(r){return r==null}function wU(r){return r!=null}async function xT(){if(typeof window<"u"&&window!==null)return"browser";try{const r=await Ei(()=>import("./__vite-browser-external-FmFgRqLi.js"),[]);return typeof r<"u"&&r.versions!=null&&r.versions.node!=null?"node":"unknown"}catch{return"unknown"}}function xU(r){return Tr(r)?!1:Ct.isInt(r.type)&&!ST(r)||SU(r)}function SU(r){return Tr(r)?!1:Ct.isInt(r.type)&&r.type.isSigned===!1}function TU(r){return Tr(r)?!1:Ct.isFloat(r.type)??!1}function IU(r){return Tr(r)?!1:Ct.isDecimal(r.type)}function EU(r){return Tr(r)?!1:Ct.isBool(r.type)}function AU(r){return Tr(r)?!1:Ct.isDuration(r.type)}function ST(r){return Tr(r)?!1:Ct.isInt(r.type)&&r.metadata.get("ARROW:extension:name")==="period"}function MU(r){return Tr(r)?!1:Ct.isTimestamp(r.type)}function CU(r){return Tr(r)?!1:Ct.isDate(r.type)}function OU(r){return Tr(r)?!1:Ct.isTime(r.type)}function PU(r){return Tr(r)?!1:Ct.isList(r.type)||Ct.isFixedSizeList(r.type)}function RU(r){return Tr(r)?!1:Ct.isStruct(r.type)||Ct.isMap(r.type)}function FU(r){return Tr(r)?!1:Ct.isStruct(r.type)&&r.metadata.get("ARROW:extension:name")==="interval"||Ct.isInterval(r.type)}function DU(r,t){let e;if(t===te.MILLISECOND)e=1e3;else if(t===te.MICROSECOND)e=1e3*1e3;else if(t===te.NANOSECOND)e=1e3*1e3*1e3;else return Number(r);return typeof r=="bigint"&&!Number.isSafeInteger(Number(r))?Number(r/BigInt(e)):Number(r)/e}function LU(r,t){var n;const e=DU(r,((n=t==null?void 0:t.type)==null?void 0:n.unit)??te.SECOND);return yU(e)}function NU(r,t){const e=LU(r,t);return wT(e,e.getMilliseconds()===0?"HH:mm:ss":"HH:mm:ss.SSS")}function BU(r){const t="yyyy-MM-dd";return r instanceof Date||typeof r=="number"&&Number.isFinite(r)?wT(r,t):(console.warn(`Unsupported date value: ${r}`),String(r))}function UU(r,t){var i;if(!(r instanceof Date||typeof r=="number"&&Number.isFinite(r)))return console.warn(`Unsupported datetime value: ${r}`),null;let e;const n=(i=t==null?void 0:t.type)==null?void 0:i.timezone;return typeof r=="number"?n?e=new Fr(r,n):e=new Fr(r):n?e=new Fr(r,n):e=new Fr(r),vU(e,Date)}function kU(r,t){var a;const e=((a=t==null?void 0:t.type)==null?void 0:a.scale)||0;let n=ev.bigNumToString(new ev.BN(r)).padStart(e,"0");if(e===0)return n;let i="";n.startsWith("-")&&(i="-",n=n.slice(1));const s=n.slice(0,-e)||"0",o=bU(n.slice(-e),"0")||"";return`${i}${s}${o?`.${o}`:""}`}function zU(r){const t=r[0],e=r[1],n=[];return t!==0&&n.push(`${t} year${t>1?"s":""}`),e!==0&&n.push(`${e} month${e>1?"s":""}`),n.length?n.join(" "):"0 months"}function VU(r,t){var n,i,s,o;if(Ct.isInterval(t==null?void 0:t.type))return zU(r);const e=t&&t.metadata.get("ARROW:extension:name");if(e&&e==="pandas.interval"){const a=JSON.parse(t.metadata.get("ARROW:extension:metadata")),{closed:l}=a,u=r.toJSON(),c=l==="both"||l==="left"?"[":"(",h=l==="both"||l==="right"?"]":")",f=pf(u.left,(i=(n=t.type)==null?void 0:n.children)==null?void 0:i[0]),d=pf(u.right,(o=(s=t.type)==null?void 0:s.children)==null?void 0:o[1]);return`${c+f}, ${d+h}`}return String(r)}function jU(r,t){return(t==null?void 0:t.type)instanceof hf?JSON.parse(JSON.stringify(r,(e,n)=>{if(wU(n))return typeof n=="bigint"?Number(n):n})):JSON.parse(JSON.stringify(r,(e,n)=>typeof n=="bigint"?Number(n):n))}function pf(r,t){if(Tr(r))return null;const e=r instanceof Date||Number.isFinite(r);if(e&&CU(t))return BU(r);if(typeof r=="bigint"&&OU(t))return NU(Number(r),t);if(e&&MU(t))return UU(r,t);if(ST(t))throw new Error("Period type is not supported yet");if(FU(t))return VU(r,t);if(AU(t))throw new Error("Duration type is not supported yet");return IU(t)?kU(r,t):TU(t)&&Number.isFinite(r)||xU(t)?r:RU(t)||PU(t)?jU(r,t):EU(t)?!!r:String(r)}function uv(r){return((r.toArray()||[]).map(n=>n.toJSON())||[]).map(n=>(r.schema.fields.forEach(i=>n[i.name]=pf(n[i.name],i)),n))}var Ha=(r=>(r.ORIGIN_PRIVATE_FS="origin-private-fs",r.NODE_FS="node-fs",r))(Ha||{});async function TT(r){const t=M1(r,{logger:!1});let e,n;const i=await xT();if(i==="browser"){if(typeof t.bundles>"u"){const{getBundles:l}=await Ei(async()=>{const{getBundles:u}=await import("./default-browser-BrgSDbLD.js");return{getBundles:u}},[]);t.bundles=await l()}n=await Iy(await t.bundles),e=new Worker(n.mainWorker)}else if(i==="node"){if(typeof t.bundles>"u"){const{getBundles:c}=await Ei(async()=>{const{getBundles:h}=await import("./default-node-CM_FKz7Y.js");return{getBundles:h}},__vite__mapDeps([0,1,2]));t.bundles=await c()}n=await Iy(await t.bundles);let l=n.mainWorker;l.startsWith("/@fs/")&&(l=l.replace("/@fs/","file://"));const u=await Ei(()=>import("./index-Cp8iQ_hy.js"),[]);e=new u.default(l,{type:"module"})}else throw new Error(`Unsupported environment: ${i}`);let s;t.logger===!0?s=new Bx:t.logger===!1?s=new PD:s=t.logger;const o=new UD(s,e);if(await o.instantiate(n.mainModule,n.pthreadWorker),t.storage)switch(t.storage.type){case Ha.ORIGIN_PRIVATE_FS:{try{let l=t.storage.path;l.startsWith("/")&&(l=l.slice(1)),await o.open({path:`opfs://${l}`,accessMode:t.storage.accessMode})}catch(l){throw await o.terminate(),await e.terminate(),l}break}case Ha.NODE_FS:{try{await o.open({path:t.storage.path,accessMode:t.storage.accessMode,useDirectIO:!0})}catch(l){throw await o.terminate(),await e.terminate(),l}break}}const a=await o.connect();return{worker:e,db:o,conn:a,query:async(l,u=[])=>{if(!u||u.length===0){const d=await a.query(l);return uv(d)}const c=await a.prepare(l),h=await c.query(...u),f=uv(h);return c.close(),f},close:async()=>{await a.close(),await o.terminate(),await e.terminate()}}}async function $U(r,t){await(await r).conn.send("BEGIN TRANSACTION");try{const e=await t(r);return await(await r).conn.send("COMMIT"),e}catch(e){throw await(await r).conn.send("ROLLBACK"),e}}async function GU(r,t,e){await(await r).conn.send(`SAVEPOINT ${t}`);try{const n=await e(r);return await(await r).conn.send(`RELEASE SAVEPOINT ${t}`),n}catch(n){throw await(await r).conn.send(`ROLLBACK TO SAVEPOINT ${t}`),n}}const St=Symbol.for("drizzle:entityKind");function lt(r,t){if(!r||typeof r!="object")return!1;if(r instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,St))throw new Error(`Class "${t.name??""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let e=Object.getPrototypeOf(r).constructor;if(e)for(;e;){if(St in e&&e[St]===t[St])return!0;e=Object.getPrototypeOf(e)}return!1}var bv;bv=St;class rr{constructor(t,e){W(this,"name");W(this,"keyAsName");W(this,"primary");W(this,"notNull");W(this,"default");W(this,"defaultFn");W(this,"onUpdateFn");W(this,"hasDefault");W(this,"isUnique");W(this,"uniqueName");W(this,"uniqueType");W(this,"dataType");W(this,"columnType");W(this,"enumValues");W(this,"generated");W(this,"generatedIdentity");W(this,"config");this.table=t,this.config=e,this.name=e.name,this.keyAsName=e.keyAsName,this.notNull=e.notNull,this.default=e.default,this.defaultFn=e.defaultFn,this.onUpdateFn=e.onUpdateFn,this.hasDefault=e.hasDefault,this.primary=e.primaryKey,this.isUnique=e.isUnique,this.uniqueName=e.uniqueName,this.uniqueType=e.uniqueType,this.dataType=e.dataType,this.columnType=e.columnType,this.generated=e.generated,this.generatedIdentity=e.generatedIdentity}mapFromDriverValue(t){return t}mapToDriverValue(t){return t}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}W(rr,bv,"Column");const Eo=Symbol.for("drizzle:Name");function WU(r,t){return`${r[Eo]}_${t.join("_")}_unique`}var wv,xv;class Lr extends(xv=rr,wv=St,xv){constructor(t,e){e.uniqueName||(e.uniqueName=WU(t,[e.name])),super(t,e),this.table=t}}W(Lr,wv,"PgColumn");const cv=Symbol.for("drizzle:isPgEnum");function HU(r){return!!r&&typeof r=="function"&&cv in r&&r[cv]===!0}var Sv;Sv=St;class Nr{constructor(t,e,n,i=!1){this._={brand:"Subquery",sql:t,selectedFields:e,alias:n,isWith:i}}}W(Nr,Sv,"Subquery");var Tv,Iv;class Lp extends(Iv=Nr,Tv=St,Iv){}W(Lp,Tv,"WithSubquery");const Ur={startActiveSpan(r,t){return t()}},Qe=Symbol.for("drizzle:ViewBaseConfig"),Kl=Symbol.for("drizzle:Schema"),mf=Symbol.for("drizzle:Columns"),hv=Symbol.for("drizzle:ExtraConfigColumns"),Vh=Symbol.for("drizzle:OriginalName"),jh=Symbol.for("drizzle:BaseName"),Wu=Symbol.for("drizzle:IsAlias"),dv=Symbol.for("drizzle:ExtraConfigBuilder"),XU=Symbol.for("drizzle:IsDrizzleTable");var Ev,Av,Mv,Cv,Ov,Pv,Rv,Fv,Dv,Lv;Lv=St,Dv=Eo,Fv=Vh,Rv=Kl,Pv=mf,Ov=hv,Cv=jh,Mv=Wu,Av=XU,Ev=dv;class Tt{constructor(t,e,n){W(this,Dv);W(this,Fv);W(this,Rv);W(this,Pv);W(this,Ov);W(this,Cv);W(this,Mv,!1);W(this,Av,!0);W(this,Ev);this[Eo]=this[Vh]=t,this[Kl]=e,this[jh]=n}}W(Tt,Lv,"Table"),W(Tt,"Symbol",{Name:Eo,Schema:Kl,OriginalName:Vh,Columns:mf,ExtraConfigColumns:hv,BaseName:jh,IsAlias:Wu,ExtraConfigBuilder:dv});function vs(r){return r[Eo]}function Xa(r){return`${r[Kl]??"public"}.${r[Eo]}`}function IT(r){return r!=null&&typeof r.getSQL=="function"}function YU(r){var e;const t={sql:"",params:[]};for(const n of r)t.sql+=n.sql,t.params.push(...n.params),(e=n.typings)!=null&&e.length&&(t.typings||(t.typings=[]),t.typings.push(...n.typings));return t}var Nv;Nv=St;class Ze{constructor(t){W(this,"value");this.value=Array.isArray(t)?t:[t]}getSQL(){return new Pt([this])}}W(Ze,Nv,"StringChunk");var Bv;Bv=St;const ps=class ps{constructor(t){W(this,"decoder",ET);W(this,"shouldInlineParams",!1);this.queryChunks=t}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return Ur.startActiveSpan("drizzle.buildSQL",e=>{const n=this.buildQueryFromSourceParams(this.queryChunks,t);return e==null||e.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(t,e){const n=Object.assign({},e,{inlineParams:e.inlineParams||this.shouldInlineParams,paramStartIndex:e.paramStartIndex||{value:0}}),{casing:i,escapeName:s,escapeParam:o,prepareTyping:a,inlineParams:l,paramStartIndex:u}=n;return YU(t.map(c=>{var h;if(lt(c,Ze))return{sql:c.value.join(""),params:[]};if(lt(c,Hu))return{sql:s(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){const f=[new Ze("(")];for(const[d,m]of c.entries())f.push(m),dr},AT={mapToDriverValue:r=>r};({...ET,...AT});var kv;kv=St;class ci{constructor(t,e=AT){W(this,"brand");this.value=t,this.encoder=e}getSQL(){return new Pt([this])}}W(ci,kv,"Param");function Y(r,...t){const e=[];(t.length>0||r.length>0&&r[0]!=="")&&e.push(new Ze(r[0]));for(const[n,i]of t.entries())e.push(i,new Ze(r[n+1]));return new Pt(e)}(r=>{function t(){return new Pt([])}r.empty=t;function e(l){return new Pt(l)}r.fromList=e;function n(l){return new Pt([new Ze(l)])}r.raw=n;function i(l,u){const c=[];for(const[h,f]of l.entries())h>0&&u!==void 0&&c.push(u),c.push(f);return new Pt(c)}r.join=i;function s(l){return new Hu(l)}r.identifier=s;function o(l){return new Ms(l)}r.placeholder=o;function a(l,u){return new ci(l,u)}r.param=a})(Y||(Y={}));(r=>{var e;e=St;const n=class n{constructor(s,o){W(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=o}getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}};W(n,e,"SQL.Aliased");let t=n;r.Aliased=t})(Pt||(Pt={}));var zv;zv=St;class Ms{constructor(t){this.name=t}getSQL(){return new Pt([this])}}W(Ms,zv,"Placeholder");function fv(r,t){return r.map(e=>{if(lt(e,Ms)){if(!(e.name in t))throw new Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(lt(e,ci)&<(e.value,Ms)){if(!(e.value.name in t))throw new Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(t[e.value.name])}return e})}const QU=Symbol.for("drizzle:IsDrizzleView");var Vv,jv,$v;$v=St,jv=Qe,Vv=QU;class ji{constructor({name:t,schema:e,selectedFields:n,query:i}){W(this,jv);W(this,Vv,!0);this[Qe]={name:t,originalName:t,schema:e,selectedFields:n,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Pt([this])}}W(ji,$v,"View");rr.prototype.getSQL=function(){return new Pt([this])};Tt.prototype.getSQL=function(){return new Pt([this])};Nr.prototype.getSQL=function(){return new Pt([this])};var Gv;Gv=St;class Ya{constructor(t){this.table=t}get(t,e){return e==="table"?this.table:t[e]}}W(Ya,Gv,"ColumnAliasProxyHandler");var Wv;Wv=St;class gc{constructor(t,e){this.alias=t,this.replaceOriginalName=e}get(t,e){if(e===Tt.Symbol.IsAlias)return!0;if(e===Tt.Symbol.Name)return this.alias;if(this.replaceOriginalName&&e===Tt.Symbol.OriginalName)return this.alias;if(e===Qe)return{...t[Qe],name:this.alias,isAlias:!0};if(e===Tt.Symbol.Columns){const i=t[Tt.Symbol.Columns];if(!i)return i;const s={};return Object.keys(i).map(o=>{s[o]=new Proxy(i[o],new Ya(new Proxy(t,this)))}),s}const n=t[e];return lt(n,rr)?new Proxy(n,new Ya(new Proxy(t,this))):n}}W(gc,Wv,"TableAliasProxyHandler");function $h(r,t){return new Proxy(r,new gc(t,!1))}function ei(r,t){return new Proxy(r,new Ya(new Proxy(r.table,new gc(t,!1))))}function MT(r,t){return new Pt.Aliased(Xu(r.sql,t),r.fieldAlias)}function Xu(r,t){return Y.join(r.queryChunks.map(e=>lt(e,rr)?ei(e,t):lt(e,Pt)?Xu(e,t):lt(e,Pt.Aliased)?MT(e,t):e))}var Hv,Xv;class Np extends(Xv=Error,Hv=St,Xv){constructor({message:t,cause:e}){super(t),this.name="DrizzleError",this.cause=e}}W(Np,Hv,"DrizzleError");var Yv,qv;class CT extends(qv=Np,Yv=St,qv){constructor(){super({message:"Rollback"})}}W(CT,Yv,"TransactionRollbackError");function Sr(r,t){return qU(t)&&!IT(r)&&!lt(r,ci)&&!lt(r,Ms)&&!lt(r,rr)&&!lt(r,Tt)&&!lt(r,ji)?new ci(r,t):r}const OT=(r,t)=>Y`${r} = ${Sr(t,r)}`,ZU=(r,t)=>Y`${r} <> ${Sr(t,r)}`;function gf(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Pt(t):new Pt([new Ze("("),Y.join(t,new Ze(" and ")),new Ze(")")])}function KU(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Pt(t):new Pt([new Ze("("),Y.join(t,new Ze(" or ")),new Ze(")")])}function JU(r){return Y`not ${r}`}const tk=(r,t)=>Y`${r} > ${Sr(t,r)}`,ek=(r,t)=>Y`${r} >= ${Sr(t,r)}`,rk=(r,t)=>Y`${r} < ${Sr(t,r)}`,nk=(r,t)=>Y`${r} <= ${Sr(t,r)}`;function ik(r,t){return Array.isArray(t)?t.length===0?Y`false`:Y`${r} in ${t.map(e=>Sr(e,r))}`:Y`${r} in ${Sr(t,r)}`}function sk(r,t){return Array.isArray(t)?t.length===0?Y`true`:Y`${r} not in ${t.map(e=>Sr(e,r))}`:Y`${r} not in ${Sr(t,r)}`}function ok(r){return Y`${r} is null`}function ak(r){return Y`${r} is not null`}function lk(r){return Y`exists ${r}`}function uk(r){return Y`not exists ${r}`}function ck(r,t,e){return Y`${r} between ${Sr(t,r)} and ${Sr(e,r)}`}function hk(r,t,e){return Y`${r} not between ${Sr(t,r)} and ${Sr(e,r)}`}function dk(r,t){return Y`${r} like ${t}`}function fk(r,t){return Y`${r} not like ${t}`}function pk(r,t){return Y`${r} ilike ${t}`}function mk(r,t){return Y`${r} not ilike ${t}`}function gk(r){return Y`${r} asc`}function yk(r){return Y`${r} desc`}var Qv;Qv=St;class PT{write(t){console.log(t)}}W(PT,Qv,"ConsoleLogWriter");var Zv;Zv=St;class RT{constructor(t){W(this,"writer");this.writer=(t==null?void 0:t.writer)??new PT}logQuery(t,e){const n=e.map(s=>{try{return JSON.stringify(s)}catch{return String(s)}}),i=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${t}${i}`)}}W(RT,Zv,"DefaultLogger");var Kv;Kv=St;class FT{logQuery(){}}W(FT,Kv,"NoopLogger");var Jv,t_;t_=St,Jv=Symbol.toStringTag;class $i{constructor(){W(this,Jv,"QueryPromise")}catch(t){return this.then(void 0,t)}finally(t){return this.then(e=>(t==null||t(),e),e=>{throw t==null||t(),e})}then(t,e){return this.execute().then(t,e)}}W($i,t_,"QueryPromise");function Cs(r,t){return Object.entries(r).reduce((e,[n,i])=>{if(typeof n!="string")return e;const s=t?[...t,n]:[n];return lt(i,rr)||lt(i,Pt)||lt(i,Pt.Aliased)?e.push({path:s,field:i}):lt(i,Tt)?e.push(...Cs(i[Tt.Symbol.Columns],s)):e.push(...Cs(i,s)),e},[])}function Bp(r,t){const e=Object.keys(r),n=Object.keys(t);if(e.length!==n.length)return!1;for(const[i,s]of e.entries())if(s!==n[i])return!1;return!0}function DT(r,t){const e=Object.entries(t).filter(([,n])=>n!==void 0).map(([n,i])=>lt(i,Pt)||lt(i,rr)?[n,i]:[n,new ci(i,r[Tt.Symbol.Columns][n])]);if(e.length===0)throw new Error("No values to set");return Object.fromEntries(e)}function vk(r,t){for(const e of t)for(const n of Object.getOwnPropertyNames(e.prototype))n!=="constructor"&&Object.defineProperty(r.prototype,n,Object.getOwnPropertyDescriptor(e.prototype,n)||Object.create(null))}function _k(r){return r[Tt.Symbol.Columns]}function fs(r){return lt(r,Nr)?r._.alias:lt(r,ji)?r[Qe].name:lt(r,Pt)?void 0:r[Tt.Symbol.IsAlias]?r[Tt.Symbol.Name]:r[Tt.Symbol.BaseName]}function bk(r){if(typeof r!="object"||r===null||r.constructor.name!=="Object")return!1;if("logger"in r){const t=typeof r.logger;return!(t!=="boolean"&&(t!=="object"||typeof r.logger.logQuery!="function")&&t!=="undefined")}if("schema"in r){const t=typeof r.logger;return!(t!=="object"&&t!=="undefined")}if("casing"in r){const t=typeof r.logger;return!(t!=="string"&&t!=="undefined")}if("mode"in r)return!(r.mode!=="default"||r.mode!=="planetscale"||r.mode!==void 0);if("connection"in r){const t=typeof r.connection;return!(t!=="string"&&t!=="object"&&t!=="undefined")}if("client"in r){const t=typeof r.client;return!(t!=="object"&&t!=="function"&&t!=="undefined")}return Object.keys(r).length===0}var e_,r_;class LT extends(r_=Lr,e_=St,r_){getSQLType(){return"date"}mapFromDriverValue(t){return new Date(t)}mapToDriverValue(t){return t.toISOString()}}W(LT,e_,"PgDate");var n_,i_;class NT extends(i_=Lr,n_=St,i_){getSQLType(){return"date"}}W(NT,n_,"PgDateString");var s_,o_;class BT extends(o_=Lr,s_=St,o_){constructor(t,e){super(t,e)}getSQLType(){return"json"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}W(BT,s_,"PgJson");var a_,l_;class UT extends(l_=Lr,a_=St,l_){constructor(t,e){super(t,e)}getSQLType(){return"jsonb"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}W(UT,a_,"PgJsonb");var u_,c_;class kT extends(c_=Lr,u_=St,c_){constructor(e,n){super(e,n);W(this,"precision");W(this,"scale");this.precision=n.precision,this.scale=n.scale}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}}W(kT,u_,"PgNumeric");var h_,d_;class zT extends(d_=Lr,h_=St,d_){constructor(e,n){super(e,n);W(this,"withTimezone");W(this,"precision");this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}W(zT,h_,"PgTime");var f_,p_;class VT extends(p_=Lr,f_=St,p_){constructor(e,n){super(e,n);W(this,"withTimezone");W(this,"precision");W(this,"mapFromDriverValue",e=>new Date(this.withTimezone?e:e+"+0000"));W(this,"mapToDriverValue",e=>e.toISOString());this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}}W(VT,f_,"PgTimestamp");var m_,g_;class jT extends(g_=Lr,m_=St,g_){constructor(e,n){super(e,n);W(this,"withTimezone");W(this,"precision");this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}W(jT,m_,"PgTimestampString");var y_,v_;class $T extends(v_=Lr,y_=St,v_){getSQLType(){return"uuid"}}W($T,y_,"PgUUID");const pv=Symbol.for("drizzle:PgInlineForeignKeys"),mv=Symbol.for("drizzle:EnableRLS");var __,b_,w_,x_,S_,T_;class Xr extends(T_=Tt,S_=St,x_=pv,w_=mv,b_=Tt.Symbol.ExtraConfigBuilder,__=Tt.Symbol.ExtraConfigColumns,T_){constructor(){super(...arguments);W(this,x_,[]);W(this,w_,!1);W(this,b_);W(this,__,{})}}W(Xr,S_,"PgTable"),W(Xr,"Symbol",Object.assign({},Tt.Symbol,{InlineForeignKeys:pv,EnableRLS:mv}));var I_;I_=St;class GT{constructor(t,e){W(this,"columns");W(this,"name");this.columns=t,this.name=e}build(t){return new WT(t,this.columns,this.name)}}W(GT,I_,"PgPrimaryKeyBuilder");var E_;E_=St;class WT{constructor(t,e,n){W(this,"columns");W(this,"name");this.table=t,this.columns=e,this.name=n}getName(){return this.name??`${this.table[Xr.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}}W(WT,E_,"PgPrimaryKey");var A_;A_=St;class Up{constructor(t,e,n){W(this,"referencedTableName");W(this,"fieldName");this.sourceTable=t,this.referencedTable=e,this.relationName=n,this.referencedTableName=e[Tt.Symbol.Name]}}W(Up,A_,"Relation");var M_;M_=St;class HT{constructor(t,e){this.table=t,this.config=e}}W(HT,M_,"Relations");var C_,O_;const Qu=class Qu extends(O_=Up,C_=St,O_){constructor(t,e,n,i){super(t,e,n==null?void 0:n.relationName),this.config=n,this.isNullable=i}withFieldName(t){const e=new Qu(this.sourceTable,this.referencedTable,this.config,this.isNullable);return e.fieldName=t,e}};W(Qu,C_,"One");let Os=Qu;var P_,R_;const Zu=class Zu extends(R_=Up,P_=St,R_){constructor(t,e,n){super(t,e,n==null?void 0:n.relationName),this.config=n}withFieldName(t){const e=new Zu(this.sourceTable,this.referencedTable,this.config);return e.fieldName=t,e}};W(Zu,P_,"Many");let Yu=Zu;function wk(){return{and:gf,between:ck,eq:OT,exists:lk,gt:tk,gte:ek,ilike:pk,inArray:ik,isNull:ok,isNotNull:ak,like:dk,lt:rk,lte:nk,ne:ZU,not:JU,notBetween:hk,notExists:uk,notLike:fk,notIlike:mk,notInArray:sk,or:KU,sql:Y}}function xk(){return{sql:Y,asc:gk,desc:yk}}function Sk(r,t){var s;Object.keys(r).length===1&&"default"in r&&!lt(r.default,Tt)&&(r=r.default);const e={},n={},i={};for(const[o,a]of Object.entries(r))if(lt(a,Tt)){const l=Xa(a),u=n[l];e[l]=o,i[o]={tsName:o,dbName:a[Tt.Symbol.Name],schema:a[Tt.Symbol.Schema],columns:a[Tt.Symbol.Columns],relations:(u==null?void 0:u.relations)??{},primaryKey:(u==null?void 0:u.primaryKey)??[]};for(const h of Object.values(a[Tt.Symbol.Columns]))h.primary&&i[o].primaryKey.push(h);const c=(s=a[Tt.Symbol.ExtraConfigBuilder])==null?void 0:s.call(a,a[Tt.Symbol.ExtraConfigColumns]);if(c)for(const h of Object.values(c))lt(h,GT)&&i[o].primaryKey.push(...h.columns)}else if(lt(a,HT)){const l=Xa(a.table),u=e[l],c=a.config(t(a.table));let h;for(const[f,d]of Object.entries(c))if(u){const m=i[u];m.relations[f]=d}else l in n||(n[l]={relations:{},primaryKey:h}),n[l].relations[f]=d}return{tables:i,tableNamesMap:e}}function Tk(r){return function(e,n){return new Os(r,e,n,(n==null?void 0:n.fields.reduce((i,s)=>i&&s.notNull,!0))??!1)}}function Ik(r){return function(e,n){return new Yu(r,e,n)}}function Ek(r,t,e){if(lt(e,Os)&&e.config)return{fields:e.config.fields,references:e.config.references};const n=t[Xa(e.referencedTable)];if(!n)throw new Error(`Table "${e.referencedTable[Tt.Symbol.Name]}" not found in schema`);const i=r[n];if(!i)throw new Error(`Table "${n}" not found in schema`);const s=e.sourceTable,o=t[Xa(s)];if(!o)throw new Error(`Table "${s[Tt.Symbol.Name]}" not found in schema`);const a=[];for(const l of Object.values(i.relations))(e.relationName&&e!==l&&l.relationName===e.relationName||!e.relationName&&l.referencedTable===e.sourceTable)&&a.push(l);if(a.length>1)throw e.relationName?new Error(`There are multiple relations with name "${e.relationName}" in table "${n}"`):new Error(`There are multiple relations between "${n}" and "${e.sourceTable[Tt.Symbol.Name]}". Please specify relation name`);if(a[0]&<(a[0],Os)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${o}.${e.fieldName}"`)}function Ak(r){return{one:Tk(r),many:Ik(r)}}function yf(r,t,e,n,i=s=>s){const s={};for(const[o,a]of n.entries())if(a.isJson){const l=t.relations[a.tsKey],u=e[o],c=typeof u=="string"?JSON.parse(u):u;s[a.tsKey]=lt(l,Os)?c&&yf(r,r[a.relationTableTsKey],c,a.selection,i):c.map(h=>yf(r,r[a.relationTableTsKey],h,a.selection,i))}else{const l=i(e[o]),u=a.field;let c;lt(u,rr)?c=u:lt(u,Pt)?c=u.decoder:c=u.sql.decoder,s[a.tsKey]=l===null?null:c.mapFromDriverValue(l)}return s}var F_;F_=St;const Ku=class Ku{constructor(t){W(this,"config");this.config={...t}}get(t,e){if(e==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(e===Qe)return{...t[Qe],selectedFields:new Proxy(t[Qe].selectedFields,this)};if(typeof e=="symbol")return t[e];const i=(lt(t,Nr)?t._.selectedFields:lt(t,ji)?t[Qe].selectedFields:t)[e];if(lt(i,Pt.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const s=i.clone();return s.isSelectionField=!0,s}if(lt(i,Pt)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${e}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return lt(i,rr)?this.config.alias?new Proxy(i,new Ya(new Proxy(i.table,new gc(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new Ku(this.config))}};W(Ku,F_,"SelectionProxyHandler");let or=Ku;var D_,L_;class vf extends(L_=$i,D_=St,L_){constructor(e,n,i,s){super();W(this,"config");W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=n,this.dialect=i,this.config={table:e,withList:s}}where(e){return this.config.where=e,this}returning(e=this.config.table[Tt.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Cs(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0))}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new or({alias:vs(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}W(vf,D_,"PgDelete");function Mk(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function Ck(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,n,i)=>{const s=i===0?n.toLowerCase():`${n[0].toUpperCase()}${n.slice(1)}`;return e+s},"")}function Ok(r){return r}var N_;N_=St;class XT{constructor(t){W(this,"cache",{});W(this,"cachedTables",{});W(this,"convert");this.convert=t==="snake_case"?Mk:t==="camelCase"?Ck:Ok}getColumnCasing(t){if(!t.keyAsName)return t.name;const e=t.table[Tt.Symbol.Schema]??"public",n=t.table[Tt.Symbol.OriginalName],i=`${e}.${n}.${t.name}`;return this.cache[i]||this.cacheTable(t.table),this.cache[i]}cacheTable(t){const e=t[Tt.Symbol.Schema]??"public",n=t[Tt.Symbol.OriginalName],i=`${e}.${n}`;if(!this.cachedTables[i]){for(const s of Object.values(t[Tt.Symbol.Columns])){const o=`${i}.${s.name}`;this.cache[o]=this.convert(s.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}W(XT,N_,"CasingCache");var B_,U_;class kp extends(U_=ji,B_=St,U_){}W(kp,B_,"PgViewBase");var k_;k_=St;class Ea{constructor(t){W(this,"casing");this.casing=new XT(t==null?void 0:t.casing)}async migrate(t,e,n){const i=typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",s=typeof n=="string"?"drizzle":n.migrationsSchema??"drizzle",o=Y` +]`}concat(...t){const e=this.schema,n=this.data.concat(t.flatMap(({data:i})=>i));return new cs(e,n.map(i=>new _r(e,i)))}slice(t,e){const n=this.schema;[t,e]=ox({length:this.numRows},t,e);const i=cx(this.data,this._offsets,t,e);return new cs(n,i.map(s=>new _r(n,s)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&tn.children[t]);if(e.length===0){const{type:n}=this.schema.fields[t],i=le({type:n,length:0,nullCount:0});e.push(i._changeLengthAndBackfillNullBitmap(this.numRows))}return new Ne(e)}return null}setChild(t,e){var n;return this.setChildAt((n=this.schema.fields)===null||n===void 0?void 0:n.findIndex(i=>i.name===t),e)}setChildAt(t,e){let n=this.schema,i=[...this.batches];if(t>-1&&tthis.getChildAt(u));[s[t],a[t]]=[o,e],[n,i]=Ph(n,a)}return new cs(n,i)}select(t){const e=this.schema.fields.reduce((n,i,s)=>n.set(i.name,s),new Map);return this.selectAt(t.map(n=>e.get(n)).filter(n=>n>-1))}selectAt(t){const e=this.schema.selectAt(t),n=this.batches.map(i=>i.selectAt(t));return new cs(e,n)}assign(t){const e=this.schema.fields,[n,i]=t.schema.fields.reduce((a,l,u)=>{const[c,h]=a,f=e.findIndex(d=>d.name===l.name);return~f?h[f]=u:c.push(u),a},[[],[]]),s=this.schema.assign(t.schema),o=[...e.map((a,l)=>[l,i[l]]).map(([a,l])=>l===void 0?this.getChildAt(a):t.getChildAt(l)),...n.map(a=>t.getChildAt(a))].filter(Boolean);return new cs(...Ph(s,o))}};bx=Symbol.toStringTag;Li[bx]=(r=>(r.schema=null,r.batches=[],r._offsets=new Uint32Array([0]),r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,r.isValid=Du(sp),r.get=Du(xr.getVisitFn(k.Struct)),r.set=hx(sn.getVisitFn(k.Struct)),r.indexOf=dx(Lu.getVisitFn(k.Struct)),"Table"))(Li.prototype);var wx;let _r=class ba{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof Le))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=le({nullCount:0,type:new dr(this.schema.fields),children:this.schema.fields.map(e=>le({type:e.type,nullCount:0}))})]=t,!(this.data instanceof Ae))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=gy(this.schema,this.data.children);break}case 1:{const[e]=t,{fields:n,children:i,length:s}=Object.keys(e).reduce((l,u,c)=>(l.children[c]=e[u],l.length=Math.max(l.length,e[u].length),l.fields[c]=Pe.new({name:u,type:e[u].type,nullable:!0}),l),{length:0,fields:new Array,children:new Array}),o=new Le(n),a=le({type:new dr(n),length:s,children:i,nullCount:0});[this.schema,this.data]=gy(o,a.children,s);break}default:throw new TypeError("RecordBatch constructor expects an Object mapping names to child Data, or a [Schema, Data] pair.")}}get dictionaries(){return this._dictionaries||(this._dictionaries=xx(this.schema.fields,this.data.children))}get numCols(){return this.schema.fields.length}get numRows(){return this.data.length}get nullCount(){return this.data.nullCount}isValid(t){return this.data.getValid(t)}get(t){return xr.visit(this.data,t)}at(t){return this.get(rp(t,this.numRows))}set(t,e){return sn.visit(this.data,t,e)}indexOf(t,e){return Lu.visit(this.data,t,e)}[Symbol.iterator](){return op.visit(new Ne([this.data]))}toArray(){return[...this]}concat(...t){return new Li(this.schema,[this,...t])}slice(t,e){const[n]=new Ne([this.data]).slice(t,e).data;return new ba(this.schema,n)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(n=>n.name===t))}getChildAt(t){return t>-1&&ti.name===t),e)}setChildAt(t,e){let n=this.schema,i=this.data;if(t>-1&&ta.name===s);~o&&(i[o]=this.data.children[o])}return new ba(e,le({type:n,length:this.numRows,children:i}))}selectAt(t){const e=this.schema.selectAt(t),n=t.map(s=>this.data.children[s]).filter(Boolean),i=le({type:new dr(e.fields),length:this.numRows,children:n});return new ba(e,i)}};wx=Symbol.toStringTag;_r[wx]=(r=>(r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(_r.prototype);function gy(r,t,e=t.reduce((n,i)=>Math.max(n,i.length),0)){var n;const i=[...r.fields],s=[...t],o=(e+63&-64)>>3;for(const[a,l]of r.fields.entries()){const u=t[a];(!u||u.length!==e)&&(i[a]=l.clone({nullable:!0}),s[a]=(n=u==null?void 0:u._changeLengthAndBackfillNullBitmap(e))!==null&&n!==void 0?n:le({type:l.type,length:e,nullCount:e,nullBitmap:new Uint8Array(o)}))}return[r.assign(i),le({type:new dr(i),length:e,children:s})]}function xx(r,t,e=new Map){var n,i;if(((n=r==null?void 0:r.length)!==null&&n!==void 0?n:0)>0&&(r==null?void 0:r.length)===(t==null?void 0:t.length))for(let s=-1,o=r.length;++sle({type:i.type})),n=le({type:new dr(t.fields),nullCount:0,children:e});super(t,n)}}let bi=class Sn{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMessage(t,e){return(e||new Sn).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+_e),(e||new Sn).__init(t.readInt32(t.position())+t.position(),t)}version(){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt16(this.bb_pos+t):je.V1}headerType(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):me.NONE}header(t){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}bodyLength(){const t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt64(this.bb_pos+t):BigInt("0")}customMetadata(t,e){const n=this.bb.__offset(this.bb_pos,12);return n?(e||new qe).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+t*4),this.bb):null}customMetadataLength(){const t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}static startMessage(t){t.startObject(5)}static addVersion(t,e){t.addFieldInt16(0,e,je.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,me.NONE)}static addHeader(t,e){t.addFieldOffset(2,e,0)}static addBodyLength(t,e){t.addFieldInt64(3,e,BigInt("0"))}static addCustomMetadata(t,e){t.addFieldOffset(4,e,0)}static createCustomMetadataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endMessage(t){return t.endObject()}static finishMessageBuffer(t,e){t.finish(e)}static finishSizePrefixedMessageBuffer(t,e){t.finish(e,void 0,!0)}static createMessage(t,e,n,i,s,o){return Sn.startMessage(t),Sn.addVersion(t,e),Sn.addHeaderType(t,n),Sn.addHeader(t,i),Sn.addBodyLength(t,s),Sn.addCustomMetadata(t,o),Sn.endMessage(t)}};class R2 extends se{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return oy.startNull(e),oy.endNull(e)}visitInt(t,e){return Cr.startInt(e),Cr.addBitWidth(e,t.bitWidth),Cr.addIsSigned(e,t.isSigned),Cr.endInt(e)}visitFloat(t,e){return Rn.startFloatingPoint(e),Rn.addPrecision(e,t.precision),Rn.endFloatingPoint(e)}visitBinary(t,e){return ey.startBinary(e),ey.endBinary(e)}visitLargeBinary(t,e){return ny.startLargeBinary(e),ny.endLargeBinary(e)}visitBool(t,e){return ry.startBool(e),ry.endBool(e)}visitUtf8(t,e){return ay.startUtf8(e),ay.endUtf8(e)}visitLargeUtf8(t,e){return iy.startLargeUtf8(e),iy.endLargeUtf8(e)}visitDecimal(t,e){return Js.startDecimal(e),Js.addScale(e,t.scale),Js.addPrecision(e,t.precision),Js.addBitWidth(e,t.bitWidth),Js.endDecimal(e)}visitDate(t,e){return Vl.startDate(e),Vl.addUnit(e,t.unit),Vl.endDate(e)}visitTime(t,e){return Zr.startTime(e),Zr.addUnit(e,t.unit),Zr.addBitWidth(e,t.bitWidth),Zr.endTime(e)}visitTimestamp(t,e){const n=t.timezone&&e.createString(t.timezone)||void 0;return Kr.startTimestamp(e),Kr.addUnit(e,t.unit),n!==void 0&&Kr.addTimezone(e,n),Kr.endTimestamp(e)}visitInterval(t,e){return Fn.startInterval(e),Fn.addUnit(e,t.unit),Fn.endInterval(e)}visitDuration(t,e){return jl.startDuration(e),jl.addUnit(e,t.unit),jl.endDuration(e)}visitList(t,e){return sy.startList(e),sy.endList(e)}visitStruct(t,e){return ys.startStruct_(e),ys.endStruct_(e)}visitUnion(t,e){vr.startTypeIdsVector(e,t.typeIds.length);const n=vr.createTypeIdsVector(e,t.typeIds);return vr.startUnion(e),vr.addMode(e,t.mode),vr.addTypeIds(e,n),vr.endUnion(e)}visitDictionary(t,e){const n=this.visit(t.indices,e);return ai.startDictionaryEncoding(e),ai.addId(e,BigInt(t.id)),ai.addIsOrdered(e,t.isOrdered),n!==void 0&&ai.addIndexType(e,n),ai.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return $l.startFixedSizeBinary(e),$l.addByteWidth(e,t.byteWidth),$l.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return Gl.startFixedSizeList(e),Gl.addListSize(e,t.listSize),Gl.endFixedSizeList(e)}visitMap(t,e){return Wl.startMap(e),Wl.addKeysSorted(e,t.keysSorted),Wl.endMap(e)}}const Rh=new R2;function F2(r,t=new Map){return new Le(L2(r,t),Yl(r.metadata),t)}function Sx(r){return new Br(r.count,Tx(r.columns),Ix(r.columns))}function D2(r){return new Vn(Sx(r.data),r.id,r.isDelta)}function L2(r,t){return(r.fields||[]).filter(Boolean).map(e=>Pe.fromJSON(e,t))}function yy(r,t){return(r.children||[]).filter(Boolean).map(e=>Pe.fromJSON(e,t))}function Tx(r){return(r||[]).reduce((t,e)=>[...t,new Ni(e.count,N2(e.VALIDITY)),...Tx(e.children)],[])}function Ix(r,t=[]){for(let e=-1,n=(r||[]).length;++et+ +(e===0),0)}function B2(r,t){let e,n,i,s,o,a;return!t||!(s=r.dictionary)?(o=_y(r,yy(r,t)),i=new Pe(r.name,o,r.nullable,Yl(r.metadata))):t.has(e=s.id)?(n=(n=s.indexType)?vy(n):new za,a=new Oo(t.get(e),n,e,s.isOrdered),i=new Pe(r.name,a,r.nullable,Yl(r.metadata))):(n=(n=s.indexType)?vy(n):new za,t.set(e,o=_y(r,yy(r,t))),a=new Oo(o,n,e,s.isOrdered),i=new Pe(r.name,a,r.nullable,Yl(r.metadata))),i||null}function Yl(r=[]){return new Map(r.map(({key:t,value:e})=>[t,e]))}function vy(r){return new Es(r.isSigned,r.bitWidth)}function _y(r,t){const e=r.type.name;switch(e){case"NONE":return new Ri;case"null":return new Ri;case"binary":return new gu;case"largebinary":return new yu;case"utf8":return new vu;case"largeutf8":return new _u;case"bool":return new bu;case"list":return new Au((t||[])[0]);case"struct":return new dr(t||[]);case"struct_":return new dr(t||[])}switch(e){case"int":{const n=r.type;return new Es(n.isSigned,n.bitWidth)}case"floatingpoint":{const n=r.type;return new mu(ar[n.precision])}case"decimal":{const n=r.type;return new wu(n.scale,n.precision,n.bitWidth)}case"date":{const n=r.type;return new xu(nn[n.unit])}case"time":{const n=r.type;return new Su(Vt[n.unit],n.bitWidth)}case"timestamp":{const n=r.type;return new Tu(Vt[n.unit],n.timezone)}case"interval":{const n=r.type;return new Iu(zn[n.unit])}case"duration":{const n=r.type;return new Eu(Vt[n.unit])}case"union":{const n=r.type,[i,...s]=(n.mode+"").toLowerCase(),o=i.toUpperCase()+s.join("");return new Mu(lr[o],n.typeIds||[],t||[])}case"fixedsizebinary":{const n=r.type;return new Cu(n.byteWidth)}case"fixedsizelist":{const n=r.type;return new Ou(n.listSize,(t||[])[0])}case"map":{const n=r.type;return new Pu((t||[])[0],n.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var U2=kb,k2=Mo;class fr{static fromJSON(t,e){const n=new fr(0,je.V5,e);return n._createHeader=z2(t,e),n}static decode(t){t=new k2(ce(t));const e=bi.getRootAsMessage(t),n=e.bodyLength(),i=e.version(),s=e.headerType(),o=new fr(n,i,s);return o._createHeader=V2(e,s),o}static encode(t){const e=new U2;let n=-1;return t.isSchema()?n=Le.encode(e,t.header()):t.isRecordBatch()?n=Br.encode(e,t.header()):t.isDictionaryBatch()&&(n=Vn.encode(e,t.header())),bi.startMessage(e),bi.addVersion(e,je.V5),bi.addHeader(e,n),bi.addHeaderType(e,t.headerType),bi.addBodyLength(e,BigInt(t.bodyLength)),bi.finishMessageBuffer(e,bi.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof Le)return new fr(0,je.V5,me.Schema,t);if(t instanceof Br)return new fr(e,je.V5,me.RecordBatch,t);if(t instanceof Vn)return new fr(e,je.V5,me.DictionaryBatch,t);throw new Error(`Unrecognized Message header: ${t}`)}get type(){return this.headerType}get version(){return this._version}get headerType(){return this._headerType}get bodyLength(){return this._bodyLength}header(){return this._createHeader()}isSchema(){return this.headerType===me.Schema}isRecordBatch(){return this.headerType===me.RecordBatch}isDictionaryBatch(){return this.headerType===me.DictionaryBatch}constructor(t,e,n,i){this._version=e,this._headerType=n,this.body=new Uint8Array(0),i&&(this._createHeader=()=>i),this._bodyLength=Te(t)}}class Br{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,n){this._nodes=e,this._buffers=n,this._length=Te(t)}}class Vn{get id(){return this._id}get data(){return this._data}get isDelta(){return this._isDelta}get length(){return this.data.length}get nodes(){return this.data.nodes}get buffers(){return this.data.buffers}constructor(t,e,n=!1){this._data=t,this._isDelta=n,this._id=Te(e)}}class Ln{constructor(t,e){this.offset=Te(t),this.length=Te(e)}}class Ni{constructor(t,e){this.length=Te(t),this.nullCount=Te(e)}}function z2(r,t){return()=>{switch(t){case me.Schema:return Le.fromJSON(r);case me.RecordBatch:return Br.fromJSON(r);case me.DictionaryBatch:return Vn.fromJSON(r)}throw new Error(`Unrecognized Message type: { name: ${me[t]}, type: ${t} }`)}}function V2(r,t){return()=>{switch(t){case me.Schema:return Le.decode(r.header(new In),new Map,r.version());case me.RecordBatch:return Br.decode(r.header(new ri),r.version());case me.DictionaryBatch:return Vn.decode(r.header(new Zs),r.version())}throw new Error(`Unrecognized Message type: { name: ${me[t]}, type: ${t} }`)}}Pe.encode=K2;Pe.decode=Q2;Pe.fromJSON=B2;Le.encode=Z2;Le.decode=j2;Le.fromJSON=F2;Br.encode=J2;Br.decode=$2;Br.fromJSON=Sx;Vn.encode=tD;Vn.decode=G2;Vn.fromJSON=D2;Ni.encode=eD;Ni.decode=H2;Ln.encode=rD;Ln.decode=W2;function j2(r,t=new Map,e=je.V5){const n=q2(r,t);return new Le(n,ql(r),t,e)}function $2(r,t=je.V5){if(r.compression()!==null)throw new Error("Record batch compression not implemented");return new Br(r.length(),X2(r),Y2(r,t))}function G2(r,t=je.V5){return new Vn(Br.decode(r.data(),t),r.id(),r.isDelta())}function W2(r){return new Ln(r.offset(),r.length())}function H2(r){return new Ni(r.length(),r.nullCount())}function X2(r){const t=[];for(let e,n=-1,i=-1,s=r.nodesLength();++nPe.encode(r,s));In.startFieldsVector(r,e.length);const n=In.createFieldsVector(r,e),i=t.metadata&&t.metadata.size>0?In.createCustomMetadataVector(r,[...t.metadata].map(([s,o])=>{const a=r.createString(`${s}`),l=r.createString(`${o}`);return qe.startKeyValue(r),qe.addKey(r,a),qe.addValue(r,l),qe.endKeyValue(r)})):-1;return In.startSchema(r),In.addFields(r,n),In.addEndianness(r,nD?Co.Little:Co.Big),i!==-1&&In.addCustomMetadata(r,i),In.endSchema(r)}function K2(r,t){let e=-1,n=-1,i=-1;const s=t.type;let o=t.typeId;Ot.isDictionary(s)?(o=s.dictionary.typeId,i=Rh.visit(s,r),n=Rh.visit(s.dictionary,r)):n=Rh.visit(s,r);const a=(s.children||[]).map(c=>Pe.encode(r,c)),l=Wr.createChildrenVector(r,a),u=t.metadata&&t.metadata.size>0?Wr.createCustomMetadataVector(r,[...t.metadata].map(([c,h])=>{const f=r.createString(`${c}`),d=r.createString(`${h}`);return qe.startKeyValue(r),qe.addKey(r,f),qe.addValue(r,d),qe.endKeyValue(r)})):-1;return t.name&&(e=r.createString(t.name)),Wr.startField(r),Wr.addType(r,n),Wr.addTypeType(r,o),Wr.addChildren(r,l),Wr.addNullable(r,!!t.nullable),e!==-1&&Wr.addName(r,e),i!==-1&&Wr.addDictionary(r,i),u!==-1&&Wr.addCustomMetadata(r,u),Wr.endField(r)}function J2(r,t){const e=t.nodes||[],n=t.buffers||[];ri.startNodesVector(r,e.length);for(const o of e.slice().reverse())Ni.encode(r,o);const i=r.endVector();ri.startBuffersVector(r,n.length);for(const o of n.slice().reverse())Ln.encode(r,o);const s=r.endVector();return ri.startRecordBatch(r),ri.addLength(r,BigInt(t.length)),ri.addNodes(r,i),ri.addBuffers(r,s),ri.endRecordBatch(r)}function tD(r,t){const e=Br.encode(r,t.data);return Zs.startDictionaryBatch(r),Zs.addId(r,BigInt(t.id)),Zs.addIsDelta(r,t.isDelta),Zs.addData(r,e),Zs.endDictionaryBatch(r)}function eD(r,t){return jb.createFieldNode(r,BigInt(t.length),BigInt(t.nullCount))}function rD(r,t){return Vb.createBuffer(r,BigInt(t.offset),BigInt(t.length))}const nD=(()=>{const r=new ArrayBuffer(2);return new DataView(r).setInt16(0,256,!0),new Int16Array(r)[0]===256})(),fp=r=>`Expected ${me[r]} Message in stream, but was null or length 0.`,pp=r=>`Header pointer of flatbuffer-encoded ${me[r]} Message is null or length 0.`,Ex=(r,t)=>`Expected to read ${r} metadata bytes, but only read ${t}.`,Ax=(r,t)=>`Expected to read ${r} bytes for message body, but only read ${t}.`;class Mx{constructor(t){this.source=t instanceof Nu?t:new Nu(t)}[Symbol.iterator](){return this}next(){let t;return(t=this.readMetadataLength()).done||t.value===-1&&(t=this.readMetadataLength()).done||(t=this.readMetadata(t.value)).done?Be:t}throw(t){return this.source.throw(t)}return(t){return this.source.return(t)}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(fp(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);const e=ce(this.source.read(t));if(e.byteLength[...i,...s.VALIDITY&&[s.VALIDITY]||[],...s.TYPE_ID&&[s.TYPE_ID]||[],...s.OFFSET&&[s.OFFSET]||[],...s.DATA&&[s.DATA]||[],...e(s.children)],[])}}readMessage(t){let e;if((e=this.next()).done)return null;if(t!=null&&e.value.headerType!==t)throw new Error(fp(t));return e.value}readSchema(){const t=me.Schema,e=this.readMessage(t),n=e==null?void 0:e.header();if(!e||!n)throw new Error(pp(t));return n}}const uc=4,sf="ARROW1",ja=new Uint8Array(sf.length);for(let r=0;rthis):this}readRecordBatch(t){return this._impl.isFile()?this._impl.readRecordBatch(t):null}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}toDOMStream(){return Yr.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return Yr.toNodeStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this},{objectMode:!0})}static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}static from(t){return t instanceof tn?t:Hd(t)?cD(t):Fb(t)?fD(t):Is(t)?Jt(this,void 0,void 0,function*(){return yield tn.from(yield t)}):Db(t)||Zf(t)||Lb(t)||Uo(t)?dD(new Po(t)):hD(new Nu(t))}static readAll(t){return t instanceof tn?t.isSync()?Sy(t):Ty(t):Hd(t)||ArrayBuffer.isView(t)||Qa(t)||Rb(t)?Sy(t):Ty(t)}}class Uu extends tn{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return br(this,arguments,function*(){yield Rt(yield*Ss(Bn(this[Symbol.iterator]())))})}}class ku extends tn{constructor(t){super(t),this._impl=t}readAll(){return Jt(this,void 0,void 0,function*(){var t,e,n,i;const s=new Array;try{for(var o=!0,a=Bn(this),l;l=yield a.next(),t=l.done,!t;o=!0){i=l.value,o=!1;const u=i;s.push(u)}}catch(u){e={error:u}}finally{try{!o&&!t&&(n=a.return)&&(yield n.call(a))}finally{if(e)throw e.error}}return s})}[Symbol.iterator](){throw new Error("AsyncRecordBatchStreamReader is not Iterable")}[Symbol.asyncIterator](){return this._impl[Symbol.asyncIterator]()}}class Ox extends Uu{constructor(t){super(t),this._impl=t}}class aD extends ku{constructor(t){super(t),this._impl=t}}class Px{get numDictionaries(){return this._dictionaryIndex}get numRecordBatches(){return this._recordBatchIndex}constructor(t=new Map){this.closed=!1,this.autoDestroy=!0,this._dictionaryIndex=0,this._recordBatchIndex=0,this.dictionaries=t}isSync(){return!1}isAsync(){return!1}isFile(){return!1}isStream(){return!1}reset(t){return this._dictionaryIndex=0,this._recordBatchIndex=0,this.schema=t,this.dictionaries=new Map,this}_loadRecordBatch(t,e){const n=this._loadVectors(t,e,this.schema.fields),i=le({type:new dr(this.schema.fields),length:t.length,children:n});return new _r(this.schema,i)}_loadDictionaryBatch(t,e){const{id:n,isDelta:i}=t,{dictionaries:s,schema:o}=this,a=s.get(n),l=o.dictionaries.get(n),u=this._loadVectors(t.data,e,[l]);return(a&&i?a.concat(new Ne(u)):new Ne(u)).memoize()}_loadVectors(t,e,n){return new _x(e,t.nodes,t.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(n)}}class zu extends Px{constructor(t,e){super(e),this._reader=Hd(t)?new sD(this._handle=t):new Mx(this._handle=t)}isSync(){return!0}isStream(){return!0}[Symbol.iterator](){return this}cancel(){!this.closed&&(this.closed=!0)&&(this.reset()._reader.return(),this._reader=null,this.dictionaries=null)}open(t){return this.closed||(this.autoDestroy=Fx(this,t),this.schema||(this.schema=this._reader.readSchema())||this.cancel()),this}throw(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.throw(t):Be}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):Be}next(){if(this.closed)return Be;let t;const{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;const n=t.header(),i=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(n,i)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const n=t.header(),i=e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(n,i);this.dictionaries.set(n.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new dp(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}}class Vu extends Px{constructor(t,e){super(e),this._reader=new iD(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Jt(this,void 0,void 0,function*(){!this.closed&&(this.closed=!0)&&(yield this.reset()._reader.return(),this._reader=null,this.dictionaries=null)})}open(t){return Jt(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=Fx(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return Jt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):Be})}return(t){return Jt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):Be})}next(){return Jt(this,void 0,void 0,function*(){if(this.closed)return Be;let t;const{_reader:e}=this;for(;t=yield this._readNextMessageAndValidate();)if(t.isSchema())yield this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;const n=t.header(),i=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(n,i)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const n=t.header(),i=yield e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(n,i);this.dictionaries.set(n.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new dp(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return Jt(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}}class Rx extends zu{get footer(){return this._footer}get numDictionaries(){return this._footer?this._footer.numDictionaries:0}get numRecordBatches(){return this._footer?this._footer.numRecordBatches:0}constructor(t,e){super(t instanceof my?t:new my(t),e)}isSync(){return!0}isFile(){return!0}open(t){if(!this.closed&&!this._footer){this.schema=(this._footer=this._readFooter()).schema;for(const e of this._footer.dictionaryBatches())e&&this._readDictionaryBatch(this._dictionaryIndex++)}return super.open(t)}readRecordBatch(t){var e;if(this.closed)return null;this._footer||this.open();const n=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(n&&this._handle.seek(n.offset)){const i=this._reader.readMessage(me.RecordBatch);if(i!=null&&i.isRecordBatch()){const s=i.header(),o=this._reader.readMessageBody(i.bodyLength);return this._loadRecordBatch(s,o)}}return null}_readDictionaryBatch(t){var e;const n=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(n&&this._handle.seek(n.offset)){const i=this._reader.readMessage(me.DictionaryBatch);if(i!=null&&i.isDictionaryBatch()){const s=i.header(),o=this._reader.readMessageBody(i.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}}_readFooter(){const{_handle:t}=this,e=t.size-Cx,n=t.readInt32(e),i=t.readAt(e-n,n);return Va.decode(i)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Jt(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const n of this._footer.dictionaryBatches())n&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){return Jt(this,void 0,void 0,function*(){var e;if(this.closed)return null;this._footer||(yield this.open());const n=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(n&&(yield this._handle.seek(n.offset))){const i=yield this._reader.readMessage(me.RecordBatch);if(i!=null&&i.isRecordBatch()){const s=i.header(),o=yield this._reader.readMessageBody(i.bodyLength);return this._loadRecordBatch(s,o)}}return null})}_readDictionaryBatch(t){return Jt(this,void 0,void 0,function*(){var e;const n=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(n&&(yield this._handle.seek(n.offset))){const i=yield this._reader.readMessage(me.DictionaryBatch);if(i!=null&&i.isDictionaryBatch()){const s=i.header(),o=yield this._reader.readMessageBody(i.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}})}_readFooter(){return Jt(this,void 0,void 0,function*(){const{_handle:t}=this;t._pending&&(yield t._pending);const e=t.size-Cx,n=yield t.readInt32(e),i=yield t.readAt(e-n,n);return Va.decode(i)})}_readNextMessageAndValidate(t){return Jt(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?mp(t)?new Ox(new Rx(r.read())):new Uu(new zu(r)):new Uu(new zu(function*(){}()))}function dD(r){return Jt(this,void 0,void 0,function*(){const t=yield r.peek(tl+7&-8);return t&&t.byteLength>=4?mp(t)?new Ox(new Rx(yield r.read())):new ku(new Vu(r)):new ku(new Vu(function(){return br(this,arguments,function*(){})}()))})}function fD(r){return Jt(this,void 0,void 0,function*(){const{size:t}=yield r.stat(),e=new Bu(r,t);return t>=oD&&mp(yield e.readAt(0,tl+7&-8))?new aD(new lD(e)):new ku(new Vu(e))})}class ke extends se{static assemble(...t){const e=i=>i.flatMap(s=>Array.isArray(s)?e(s):s instanceof _r?s.data.children:s.data),n=new ke;return n.visitMany(e(t)),n}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof Ne)return this.visitMany(t.data),this;const{type:e}=t;if(!Ot.isDictionary(e)){const{length:n}=t;if(n>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");if(Ot.isUnion(e))this.nodes.push(new Ni(n,0));else{const{nullCount:i}=t;Ot.isNull(e)||dn.call(this,i<=0?new Uint8Array(0):Ru(t.offset,n,t.nullBitmap)),this.nodes.push(new Ni(n,i))}}return super.visit(t)}visitNull(t){return this}visitDictionary(t){return this.visit(t.clone(t.type.indices))}get nodes(){return this._nodes}get buffers(){return this._buffers}get byteLength(){return this._byteLength}get bufferRegions(){return this._bufferRegions}}function dn(r){const t=r.byteLength+7&-8;return this.buffers.push(r),this.bufferRegions.push(new Ln(this._byteLength,t)),this._byteLength+=t,this}function pD(r){var t;const{type:e,length:n,typeIds:i,valueOffsets:s}=r;if(dn.call(this,i),e.mode===lr.Sparse)return of.call(this,r);if(e.mode===lr.Dense){if(r.offset<=0)return dn.call(this,s),of.call(this,r);{const o=new Int32Array(n),a=Object.create(null),l=Object.create(null);for(let u,c,h=-1;++h{const h=e.typeIds[c],f=a[h],d=l[h];return u.slice(f,Math.min(n,d))}))}}return this}function mD(r){let t;return r.nullCount>=r.length?dn.call(this,new Uint8Array(0)):(t=r.values)instanceof Uint8Array?dn.call(this,Ru(r.offset,r.length,t)):dn.call(this,Fu(r.values))}function fi(r){return dn.call(this,r.values.subarray(0,r.length*r.stride))}function cc(r){const{length:t,values:e,valueOffsets:n}=r,i=Te(n[0]),s=Te(n[t]),o=Math.min(s-i,e.byteLength-i);return dn.call(this,Bb(-i,t+1,n)),dn.call(this,e.subarray(i,i+o)),this}function gp(r){const{length:t,valueOffsets:e}=r;if(e){const{[0]:n,[t]:i}=e;return dn.call(this,Bb(-n,t+1,e)),this.visit(r.children[0].slice(n,i-n))}return this.visit(r.children[0])}function of(r){return this.visitMany(r.type.children.map((t,e)=>r.children[e]).filter(Boolean))[0]}ke.prototype.visitBool=mD;ke.prototype.visitInt=fi;ke.prototype.visitFloat=fi;ke.prototype.visitUtf8=cc;ke.prototype.visitLargeUtf8=cc;ke.prototype.visitBinary=cc;ke.prototype.visitLargeBinary=cc;ke.prototype.visitFixedSizeBinary=fi;ke.prototype.visitDate=fi;ke.prototype.visitTimestamp=fi;ke.prototype.visitTime=fi;ke.prototype.visitDecimal=fi;ke.prototype.visitList=gp;ke.prototype.visitStruct=of;ke.prototype.visitUnion=pD;ke.prototype.visitInterval=fi;ke.prototype.visitDuration=fi;ke.prototype.visitFixedSizeList=gp;ke.prototype.visitMap=gp;class Dx extends ap{static throughNode(t){throw new Error('"throughNode" not available in this environment')}static throughDOM(t,e){throw new Error('"throughDOM" not available in this environment')}constructor(t){super(),this._position=0,this._started=!1,this._sink=new Xl,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,wr(t)||(t={autoDestroy:!0,writeLegacyIpcFormat:!1}),this._autoDestroy=typeof t.autoDestroy=="boolean"?t.autoDestroy:!0,this._writeLegacyIpcFormat=typeof t.writeLegacyIpcFormat=="boolean"?t.writeLegacyIpcFormat:!1}toString(t=!1){return this._sink.toString(t)}toUint8Array(t=!1){return this._sink.toUint8Array(t)}writeAll(t){return Is(t)?t.then(e=>this.writeAll(e)):Uo(t)?bp(this,t):_p(this,t)}get closed(){return this._sink.closed}[Symbol.asyncIterator](){return this._sink[Symbol.asyncIterator]()}toDOMStream(t){return this._sink.toDOMStream(t)}toNodeStream(t){return this._sink.toNodeStream(t)}close(){return this.reset()._sink.close()}abort(t){return this.reset()._sink.abort(t)}finish(){return this._autoDestroy?this.close():this.reset(this._sink,this._schema),this}reset(t=this._sink,e=null){return t===this._sink||t instanceof Xl?this._sink=t:(this._sink=new Xl,t&&GR(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&WR(t)&&this.toNodeStream({objectMode:!1}).pipe(t)),this._started&&this._schema&&this._writeFooter(this._schema),this._started=!1,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,(!e||!nf(e,this._schema))&&(e==null?(this._position=0,this._schema=null):(this._started=!0,this._schema=e,this._writeSchema(e))),this}write(t){let e=null;if(this._sink){if(t==null)return this.finish()&&void 0;if(t instanceof Li&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof _r&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!nf(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof _r?t instanceof dp||this._writeRecordBatch(t):t instanceof Li?this.writeAll(t.batches):Qa(t)&&this.writeAll(t)}_writeMessage(t,e=8){const n=e-1,i=fr.encode(t),s=i.byteLength,o=this._writeLegacyIpcFormat?4:8,a=s+o+n&~n,l=a-s-o;return t.headerType===me.RecordBatch?this._recordBatchBlocks.push(new Fi(a,t.bodyLength,this._position)):t.headerType===me.DictionaryBatch&&this._dictionaryBlocks.push(new Fi(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-o)),s>0&&this._write(i),this._writePadding(l)}_write(t){if(this._started){const e=ce(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(fr.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(ja)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){const{byteLength:e,nodes:n,bufferRegions:i,buffers:s}=ke.assemble(t),o=new Br(t.numRows,n,i),a=fr.from(o,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(s)}_writeDictionaryBatch(t,e,n=!1){const{byteLength:i,nodes:s,bufferRegions:o,buffers:a}=ke.assemble(new Ne([t])),l=new Br(t.length,s,o),u=new Vn(l,e,n),c=fr.from(u,i);return this._writeMessage(c)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,n,i;for(let s=-1,o=t.length;++s0&&(this._write(e),(i=(n+7&-8)-n)>0&&this._writePadding(i));return this}_writeDictionaries(t){var e,n;for(const[i,s]of t.dictionaries){const o=(e=s==null?void 0:s.data)!==null&&e!==void 0?e:[],a=this._seenDictionaries.get(i),l=(n=this._dictionaryDeltaOffsets.get(i))!==null&&n!==void 0?n:0;if(!a||a.data[0]!==o[0])for(const[u,c]of o.entries())this._writeDictionaryBatch(c,i,u>0);else if(ln.writeAll(i)):Uo(t)?bp(n,t):_p(n,t)}}class vp extends Dx{static writeAll(t){const e=new vp;return Is(t)?t.then(n=>e.writeAll(n)):Uo(t)?bp(e,t):_p(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(t,e,n=!1){if(!n&&this._seenDictionaries.has(e))throw new Error("The Arrow File format does not support replacement dictionaries. ");return super._writeDictionaryBatch(t,e,n)}_writeFooter(t){const e=Va.encode(new Va(t,je.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}}function _p(r,t){let e=t;t instanceof Li&&(e=t.batches,r.reset(void 0,t.schema));for(const n of e)r.write(n);return r.finish()}function bp(r,t){return Jt(this,void 0,void 0,function*(){var e,n,i,s,o,a,l;try{for(e=!0,n=Bn(t);i=yield n.next(),s=i.done,!s;e=!0){l=i.value,e=!1;const u=l;r.write(u)}}catch(u){o={error:u}}finally{try{!e&&!s&&(a=n.return)&&(yield a.call(n))}finally{if(o)throw o.error}}return r.finish()})}function gD(r,t="stream"){return(t==="stream"?yp:vp).writeAll(r).toUint8Array(!0)}var yD=Object.create,Lx=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,_D=Object.getOwnPropertyNames,bD=Object.getPrototypeOf,wD=Object.prototype.hasOwnProperty,xD=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),SD=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of _D(t))!wD.call(r,i)&&i!==e&&Lx(r,i,{get:()=>t[i],enumerable:!(n=vD(t,i))||n.enumerable});return r},TD=(r,t,e)=>(e=r!=null?yD(bD(r)):{},SD(!r||!r.__esModule?Lx(e,"default",{value:r,enumerable:!0}):e,r)),ID=xD((r,t)=>{t.exports=Worker}),Nx=(r=>(r[r.UNDEFINED=0]="UNDEFINED",r[r.AUTOMATIC=1]="AUTOMATIC",r[r.READ_ONLY=2]="READ_ONLY",r[r.READ_WRITE=3]="READ_WRITE",r))(Nx||{}),ED=(r=>(r[r.IDENTIFIER=0]="IDENTIFIER",r[r.NUMERIC_CONSTANT=1]="NUMERIC_CONSTANT",r[r.STRING_CONSTANT=2]="STRING_CONSTANT",r[r.OPERATOR=3]="OPERATOR",r[r.KEYWORD=4]="KEYWORD",r[r.COMMENT=5]="COMMENT",r))(ED||{}),AD=(r=>(r[r.NONE=0]="NONE",r[r.DEBUG=1]="DEBUG",r[r.INFO=2]="INFO",r[r.WARNING=3]="WARNING",r[r.ERROR=4]="ERROR",r))(AD||{}),MD=(r=>(r[r.NONE=0]="NONE",r[r.CONNECT=1]="CONNECT",r[r.DISCONNECT=2]="DISCONNECT",r[r.OPEN=3]="OPEN",r[r.QUERY=4]="QUERY",r[r.INSTANTIATE=5]="INSTANTIATE",r))(MD||{}),CD=(r=>(r[r.NONE=0]="NONE",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR",r[r.START=3]="START",r[r.RUN=4]="RUN",r[r.CAPTURE=5]="CAPTURE",r))(CD||{}),OD=(r=>(r[r.NONE=0]="NONE",r[r.WEB_WORKER=1]="WEB_WORKER",r[r.NODE_WORKER=2]="NODE_WORKER",r[r.BINDINGS=3]="BINDINGS",r[r.ASYNC_DUCKDB=4]="ASYNC_DUCKDB",r))(OD||{}),PD=class{log(r){}},Bx=class{constructor(r=2){this.level=r}log(r){r.level>=this.level&&console.log(r)}},RD=(r=>(r[r.SUCCESS=0]="SUCCESS",r))(RD||{}),FD=class{constructor(r,t){this._bindings=r,this._conn=t}get bindings(){return this._bindings}async close(){return this._bindings.disconnect(this._conn)}useUnsafe(r){return r(this._bindings,this._conn)}async query(r){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let t=await this._bindings.runQuery(this._conn,r),e=tn.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new Li(e)}async send(r,t=!1){this._bindings.logger.log({timestamp:new Date,level:2,origin:4,topic:4,event:4,value:r});let e=await this._bindings.startPendingQuery(this._conn,r,t);for(;e==null;)e=await this._bindings.pollPendingQuery(this._conn);let n=new Ux(this._bindings,this._conn,e),i=await tn.from(n);return console.assert(i.isAsync()),console.assert(i.isStream()),i}async cancelSent(){return await this._bindings.cancelPendingQuery(this._conn)}async getTableNames(r){return await this._bindings.getTableNames(this._conn,r)}async prepare(r){let t=await this._bindings.createPrepared(this._conn,r);return new DD(this._bindings,this._conn,t)}async insertArrowTable(r,t){let e=gD(r,"stream");await this.insertArrowFromIPCStream(e,t)}async insertArrowFromIPCStream(r,t){await this._bindings.insertArrowFromIPCStream(this._conn,r,t)}async insertCSVFromPath(r,t){await this._bindings.insertCSVFromPath(this._conn,r,t)}async insertJSONFromPath(r,t){await this._bindings.insertJSONFromPath(this._conn,r,t)}},Ux=class{constructor(r,t,e){this.db=r,this.conn=t,this.header=e,this._first=!0,this._depleted=!1,this._inFlight=null}async next(){if(this._first)return this._first=!1,{done:!1,value:this.header};if(this._depleted)return{done:!0,value:null};let r;return this._inFlight!=null?(r=await this._inFlight,this._inFlight=null):r=await this.db.fetchQueryResults(this.conn),this._depleted=r.length==0,this._depleted||(this._inFlight=this.db.fetchQueryResults(this.conn)),{done:this._depleted,value:r}}[Symbol.asyncIterator](){return this}},DD=class{constructor(r,t,e){this.bindings=r,this.connectionId=t,this.statementId=e}async close(){await this.bindings.closePrepared(this.connectionId,this.statementId)}async query(...r){let t=await this.bindings.runPrepared(this.connectionId,this.statementId,r),e=tn.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new Li(e)}async send(...r){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,r),e=new Ux(this.bindings,this.connectionId,t),n=await tn.from(e);return console.assert(n.isAsync()),console.assert(n.isStream()),n}},LD=(r=>(r.CANCEL_PENDING_QUERY="CANCEL_PENDING_QUERY",r.CLOSE_PREPARED="CLOSE_PREPARED",r.COLLECT_FILE_STATISTICS="COLLECT_FILE_STATISTICS",r.REGISTER_OPFS_FILE_NAME="REGISTER_OPFS_FILE_NAME",r.CONNECT="CONNECT",r.COPY_FILE_TO_BUFFER="COPY_FILE_TO_BUFFER",r.COPY_FILE_TO_PATH="COPY_FILE_TO_PATH",r.CREATE_PREPARED="CREATE_PREPARED",r.DISCONNECT="DISCONNECT",r.DROP_FILE="DROP_FILE",r.DROP_FILES="DROP_FILES",r.EXPORT_FILE_STATISTICS="EXPORT_FILE_STATISTICS",r.FETCH_QUERY_RESULTS="FETCH_QUERY_RESULTS",r.FLUSH_FILES="FLUSH_FILES",r.GET_FEATURE_FLAGS="GET_FEATURE_FLAGS",r.GET_TABLE_NAMES="GET_TABLE_NAMES",r.GET_VERSION="GET_VERSION",r.GLOB_FILE_INFOS="GLOB_FILE_INFOS",r.INSERT_ARROW_FROM_IPC_STREAM="INSERT_ARROW_FROM_IPC_STREAM",r.INSERT_CSV_FROM_PATH="IMPORT_CSV_FROM_PATH",r.INSERT_JSON_FROM_PATH="IMPORT_JSON_FROM_PATH",r.INSTANTIATE="INSTANTIATE",r.OPEN="OPEN",r.PING="PING",r.POLL_PENDING_QUERY="POLL_PENDING_QUERY",r.REGISTER_FILE_BUFFER="REGISTER_FILE_BUFFER",r.REGISTER_FILE_HANDLE="REGISTER_FILE_HANDLE",r.REGISTER_FILE_URL="REGISTER_FILE_URL",r.RESET="RESET",r.RUN_PREPARED="RUN_PREPARED",r.RUN_QUERY="RUN_QUERY",r.SEND_PREPARED="SEND_PREPARED",r.START_PENDING_QUERY="START_PENDING_QUERY",r.TOKENIZE="TOKENIZE",r))(LD||{}),ND=(r=>(r.CONNECTION_INFO="CONNECTION_INFO",r.ERROR="ERROR",r.FEATURE_FLAGS="FEATURE_FLAGS",r.FILE_BUFFER="FILE_BUFFER",r.FILE_INFOS="FILE_INFOS",r.FILE_SIZE="FILE_SIZE",r.FILE_STATISTICS="FILE_STATISTICS",r.INSTANTIATE_PROGRESS="INSTANTIATE_PROGRESS",r.LOG="LOG",r.OK="OK",r.PREPARED_STATEMENT_ID="PREPARED_STATEMENT_ID",r.QUERY_PLAN="QUERY_PLAN",r.QUERY_RESULT="QUERY_RESULT",r.QUERY_RESULT_CHUNK="QUERY_RESULT_CHUNK",r.QUERY_RESULT_HEADER="QUERY_RESULT_HEADER",r.QUERY_RESULT_HEADER_OR_NULL="QUERY_RESULT_HEADER_OR_NULL",r.REGISTERED_FILE="REGISTERED_FILE",r.SCRIPT_TOKENS="SCRIPT_TOKENS",r.SUCCESS="SUCCESS",r.TABLE_NAMES="TABLE_NAMES",r.VERSION_STRING="VERSION_STRING",r))(ND||{}),de=class{constructor(r,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=r,this.data=t,this.promise=new Promise((e,n)=>{this.promiseResolver=e,this.promiseRejecter=n})}};function Ql(r){switch(r.typeId){case k.Binary:return{sqlType:"binary"};case k.Bool:return{sqlType:"bool"};case k.Date:return{sqlType:"date"};case k.DateDay:return{sqlType:"date32[d]"};case k.DateMillisecond:return{sqlType:"date64[ms]"};case k.Decimal:{let t=r;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case k.Float:return{sqlType:"float"};case k.Float16:return{sqlType:"float16"};case k.Float32:return{sqlType:"float32"};case k.Float64:return{sqlType:"float64"};case k.Int:return{sqlType:"int32"};case k.Int16:return{sqlType:"int16"};case k.Int32:return{sqlType:"int32"};case k.Int64:return{sqlType:"int64"};case k.Uint16:return{sqlType:"uint16"};case k.Uint32:return{sqlType:"uint32"};case k.Uint64:return{sqlType:"uint64"};case k.Uint8:return{sqlType:"uint8"};case k.IntervalDayTime:return{sqlType:"interval[dt]"};case k.IntervalYearMonth:return{sqlType:"interval[m]"};case k.List:return{sqlType:"list",valueType:Ql(r.valueType)};case k.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:r.byteWidth};case k.Null:return{sqlType:"null"};case k.Utf8:return{sqlType:"utf8"};case k.Struct:return{sqlType:"struct",fields:r.children.map(t=>af(t.name,t.type))};case k.Map:{let t=r;return{sqlType:"map",keyType:Ql(t.keyType),valueType:Ql(t.valueType)}}case k.Time:return{sqlType:"time[s]"};case k.TimeMicrosecond:return{sqlType:"time[us]"};case k.TimeMillisecond:return{sqlType:"time[ms]"};case k.TimeNanosecond:return{sqlType:"time[ns]"};case k.TimeSecond:return{sqlType:"time[s]"};case k.Timestamp:return{sqlType:"timestamp",timezone:r.timezone||void 0};case k.TimestampSecond:return{sqlType:"timestamp[s]",timezone:r.timezone||void 0};case k.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:r.timezone||void 0};case k.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:r.timezone||void 0};case k.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:r.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(r.toString()))}function af(r,t){let e=Ql(t);return e.name=r,e}var BD=new TextEncoder,UD=class{constructor(r,t=null){this._onInstantiationProgress=[],this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{},this._nextMessageId=0,this._pendingRequests=new Map,this._logger=r,this._onMessageHandler=this.onMessage.bind(this),this._onErrorHandler=this.onError.bind(this),this._onCloseHandler=this.onClose.bind(this),t!=null&&this.attach(t)}get logger(){return this._logger}attach(r){this._worker=r,this._worker.addEventListener("message",this._onMessageHandler),this._worker.addEventListener("error",this._onErrorHandler),this._worker.addEventListener("close",this._onCloseHandler),this._workerShutdownPromise=new Promise((t,e)=>{this._workerShutdownResolver=t})}detach(){this._worker&&(this._worker.removeEventListener("message",this._onMessageHandler),this._worker.removeEventListener("error",this._onErrorHandler),this._worker.removeEventListener("close",this._onCloseHandler),this._worker=null,this._workerShutdownResolver(null),this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async terminate(){this._worker&&(this._worker.terminate(),this._worker=null,this._workerShutdownPromise=null,this._workerShutdownResolver=()=>{})}async postTask(r,t=[]){if(!this._worker){console.error("cannot send a message since the worker is not set!");return}let e=this._nextMessageId++;return this._pendingRequests.set(e,r),this._worker.postMessage({messageId:e,type:r.type,data:r.data},t),await r.promise}onMessage(r){var t;let e=r.data;switch(e.type){case"LOG":{this._logger.log(e.data);return}case"INSTANTIATE_PROGRESS":{for(let i of this._onInstantiationProgress)i(e.data);return}}let n=this._pendingRequests.get(e.requestId);if(!n){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let i=new Error(e.data.message);i.name=e.data.name,(t=Object.getOwnPropertyDescriptor(i,"stack"))!=null&&t.writable&&(i.stack=e.data.stack),n.promiseRejecter(i);return}switch(n.type){case"CLOSE_PREPARED":case"COLLECT_FILE_STATISTICS":case"REGISTER_OPFS_FILE_NAME":case"COPY_FILE_TO_PATH":case"DISCONNECT":case"DROP_FILE":case"DROP_FILES":case"FLUSH_FILES":case"INSERT_ARROW_FROM_IPC_STREAM":case"IMPORT_CSV_FROM_PATH":case"IMPORT_JSON_FROM_PATH":case"OPEN":case"PING":case"REGISTER_FILE_BUFFER":case"REGISTER_FILE_HANDLE":case"REGISTER_FILE_URL":case"RESET":if(e.type=="OK"){n.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){n.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){n.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){n.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){n.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){n.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){n.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){n.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){n.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){n.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){n.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){n.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){n.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){n.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){n.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){n.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){n.promiseResolver(e.data);return}break}n.promiseRejecter(new Error("unexpected response type: ".concat(e.type.toString())))}onError(r){console.error(r),console.error("error in duckdb worker: ".concat(r.message)),this._pendingRequests.clear()}onClose(){if(this._workerShutdownResolver(null),this._pendingRequests.size!=0){console.warn("worker terminated with ".concat(this._pendingRequests.size," pending requests"));return}this._pendingRequests.clear()}async reset(){let r=new de("RESET",null);return await this.postTask(r)}async ping(){let r=new de("PING",null);await this.postTask(r)}async dropFile(r){let t=new de("DROP_FILE",r);return await this.postTask(t)}async dropFiles(){let r=new de("DROP_FILES",null);return await this.postTask(r)}async flushFiles(){let r=new de("FLUSH_FILES",null);return await this.postTask(r)}async instantiate(r,t=null,e=n=>{}){this._onInstantiationProgress.push(e);let n=new de("INSTANTIATE",[r,t]);return await this.postTask(n)}async getVersion(){let r=new de("GET_VERSION",null);return await this.postTask(r)}async getFeatureFlags(){let r=new de("GET_FEATURE_FLAGS",null);return await this.postTask(r)}async open(r){let t=new de("OPEN",r);await this.postTask(t)}async tokenize(r){let t=new de("TOKENIZE",r);return await this.postTask(t)}async connectInternal(){let r=new de("CONNECT",null);return await this.postTask(r)}async connect(){let r=await this.connectInternal();return new FD(this,r)}async disconnect(r){let t=new de("DISCONNECT",r);await this.postTask(t)}async runQuery(r,t){let e=new de("RUN_QUERY",[r,t]);return await this.postTask(e)}async startPendingQuery(r,t,e=!1){let n=new de("START_PENDING_QUERY",[r,t,e]);return await this.postTask(n)}async pollPendingQuery(r){let t=new de("POLL_PENDING_QUERY",r);return await this.postTask(t)}async cancelPendingQuery(r){let t=new de("CANCEL_PENDING_QUERY",r);return await this.postTask(t)}async fetchQueryResults(r){let t=new de("FETCH_QUERY_RESULTS",r);return await this.postTask(t)}async getTableNames(r,t){let e=new de("GET_TABLE_NAMES",[r,t]);return await this.postTask(e)}async createPrepared(r,t){let e=new de("CREATE_PREPARED",[r,t]);return await this.postTask(e)}async closePrepared(r,t){let e=new de("CLOSE_PREPARED",[r,t]);await this.postTask(e)}async runPrepared(r,t,e){let n=new de("RUN_PREPARED",[r,t,e]);return await this.postTask(n)}async sendPrepared(r,t,e){let n=new de("SEND_PREPARED",[r,t,e]);return await this.postTask(n)}async globFiles(r){let t=new de("GLOB_FILE_INFOS",r);return await this.postTask(t)}async registerFileText(r,t){let e=BD.encode(t);await this.registerFileBuffer(r,e)}async registerFileURL(r,t,e,n){t===void 0&&(t=r);let i=new de("REGISTER_FILE_URL",[r,t,e,n]);await this.postTask(i)}async registerEmptyFileBuffer(r){}async registerFileBuffer(r,t){let e=new de("REGISTER_FILE_BUFFER",[r,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(r,t,e,n){let i=new de("REGISTER_FILE_HANDLE",[r,t,e,n]);await this.postTask(i,[])}async registerOPFSFileName(r){let t=new de("REGISTER_OPFS_FILE_NAME",[r]);await this.postTask(t,[])}async collectFileStatistics(r,t){let e=new de("COLLECT_FILE_STATISTICS",[r,t]);await this.postTask(e,[])}async exportFileStatistics(r){let t=new de("EXPORT_FILE_STATISTICS",r);return await this.postTask(t,[])}async copyFileToBuffer(r){let t=new de("COPY_FILE_TO_BUFFER",r);return await this.postTask(t)}async copyFileToPath(r,t){let e=new de("COPY_FILE_TO_PATH",[r,t]);await this.postTask(e)}async insertArrowFromIPCStream(r,t,e){if(t.length==0)return;let n=new de("INSERT_ARROW_FROM_IPC_STREAM",[r,t,e]);await this.postTask(n,[t.buffer])}async insertCSVFromPath(r,t,e){if(e.columns!==void 0){let i=[];for(let s in e.columns){let o=e.columns[s];i.push(af(s,o))}e.columnsFlat=i,delete e.columns}let n=new de("IMPORT_CSV_FROM_PATH",[r,t,e]);await this.postTask(n)}async insertJSONFromPath(r,t,e){if(e.columns!==void 0){let i=[];for(let s in e.columns){let o=e.columns[s];i.push(af(s,o))}e.columnsFlat=i,delete e.columns}let n=new de("IMPORT_JSON_FROM_PATH",[r,t,e]);await this.postTask(n)}};function kD(){let r=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),r.decode(t))}kD();var zD=(r=>(r[r.BUFFER=0]="BUFFER",r[r.NODE_FS=1]="NODE_FS",r[r.BROWSER_FILEREADER=2]="BROWSER_FILEREADER",r[r.BROWSER_FSACCESS=3]="BROWSER_FSACCESS",r[r.HTTP=4]="HTTP",r[r.S3=5]="S3",r))(zD||{}),VD=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),jD=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),$D=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),GD=()=>(async r=>{try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(r)}catch{return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),WD={version:"1.29.1-dev68.0"},wp=WD.version.split(".");wp[0];wp[1];wp[2];var HD=()=>typeof navigator>"u",Fh=null,Dh=null,Lh=null,Nh=null,Bh=null;async function XD(){return Fh==null&&(Fh=typeof BigInt64Array<"u"),Dh==null&&(Dh=await jD()),Lh==null&&(Lh=await GD()),Nh==null&&(Nh=await $D()),Bh==null&&(Bh=await VD()),{bigInt64Array:Fh,crossOriginIsolated:HD()||globalThis.crossOriginIsolated||!1,wasmExceptions:Dh,wasmSIMD:Nh,wasmThreads:Lh,wasmBulkMemory:Bh}}async function Iy(r){let t=await XD();if(t.wasmExceptions){if(t.wasmSIMD&&t.wasmThreads&&t.crossOriginIsolated&&r.coi)return{mainModule:r.coi.mainModule,mainWorker:r.coi.mainWorker,pthreadWorker:r.coi.pthreadWorker};if(r.eh)return{mainModule:r.eh.mainModule,mainWorker:r.eh.mainWorker,pthreadWorker:null}}return{mainModule:r.mvp.mainModule,mainWorker:r.mvp.mainWorker,pthreadWorker:null}}TD(ID());const Uh={},wa={};function Ia(r,t){try{const n=(Uh[r]||(Uh[r]=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour:"numeric",timeZoneName:"longOffset"}).format))(t).split("GMT")[1]||"";return n in wa?wa[n]:Ey(n,n.split(":"))}catch{if(r in wa)return wa[r];const e=r==null?void 0:r.match(YD);return e?Ey(r,e.slice(1)):NaN}}const YD=/([+-]\d\d):?(\d\d)?/;function Ey(r,t){const e=+t[0],n=+(t[1]||0);return wa[r]=e>0?e*60+n:e*60-n}class Fr extends Date{constructor(...t){super(),t.length>1&&typeof t[t.length-1]=="string"&&(this.timeZone=t.pop()),this.internal=new Date,isNaN(Ia(this.timeZone,this))?this.setTime(NaN):t.length?typeof t[0]=="number"&&(t.length===1||t.length===2&&typeof t[1]!="number")?this.setTime(t[0]):typeof t[0]=="string"?this.setTime(+new Date(t[0])):t[0]instanceof Date?this.setTime(+t[0]):(this.setTime(+new Date(...t)),kx(this),lf(this)):this.setTime(Date.now())}static tz(t,...e){return e.length?new Fr(...e,t):new Fr(Date.now(),t)}withTimeZone(t){return new Fr(+this,t)}getTimezoneOffset(){return-Ia(this.timeZone,this)}setTime(t){return Date.prototype.setTime.apply(this,arguments),lf(this),+this}[Symbol.for("constructDateFrom")](t){return new Fr(+new Date(t),this.timeZone)}}const Ay=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(r=>{if(!Ay.test(r))return;const t=r.replace(Ay,"$1UTC");Fr.prototype[t]&&(r.startsWith("get")?Fr.prototype[r]=function(){return this.internal[t]()}:(Fr.prototype[r]=function(){return Date.prototype[t].apply(this.internal,arguments),qD(this),+this},Fr.prototype[t]=function(){return Date.prototype[t].apply(this,arguments),lf(this),+this}))});function lf(r){r.internal.setTime(+r),r.internal.setUTCMinutes(r.internal.getUTCMinutes()-r.getTimezoneOffset())}function qD(r){Date.prototype.setFullYear.call(r,r.internal.getUTCFullYear(),r.internal.getUTCMonth(),r.internal.getUTCDate()),Date.prototype.setHours.call(r,r.internal.getUTCHours(),r.internal.getUTCMinutes(),r.internal.getUTCSeconds(),r.internal.getUTCMilliseconds()),kx(r)}function kx(r){const t=Ia(r.timeZone,r),e=new Date(+r);e.setUTCHours(e.getUTCHours()-1);const n=-new Date(+r).getTimezoneOffset(),i=-new Date(+e).getTimezoneOffset(),s=n-i,o=Date.prototype.getHours.apply(r)!==r.internal.getUTCHours();s&&o&&r.internal.setUTCMinutes(r.internal.getUTCMinutes()+s);const a=n-t;a&&Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+a);const l=Ia(r.timeZone,r),c=-new Date(+r).getTimezoneOffset()-l,h=l!==t,f=c-a;if(h&&f){Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+f);const d=Ia(r.timeZone,r),m=l-d;m&&(r.internal.setUTCMinutes(r.internal.getUTCMinutes()+m),Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+m))}}const QD=new TextDecoder("utf-8"),ZD=r=>QD.decode(r),KD=new TextEncoder,zx=r=>KD.encode(r),An=r=>typeof r=="function",el=r=>r!=null&&Object(r)===r,JD=r=>el(r)&&An(r.then),Vx=r=>el(r)&&An(r[Symbol.iterator]),tL=r=>el(r)&&An(r[Symbol.asyncIterator]),eL=r=>el(r)&&"done"in r&&"value"in r,rL=r=>el(r)&&An(r.clear)&&An(r.bytes)&&An(r.position)&&An(r.setPosition)&&An(r.capacity)&&An(r.getBufferIdentifier)&&An(r.createLong),xp=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function nL(r){const t=r[0]?[r[0]]:[];let e,n,i,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let i,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,n);for(const c=e.length;++lur(Int8Array,r),oL=r=>ur(Int16Array,r),aL=r=>ur(Int32Array,r),lL=r=>ur(BigInt64Array,r),uL=r=>ur(Uint8Array,r),cL=r=>ur(Uint16Array,r),hL=r=>ur(Uint32Array,r),dL=r=>ur(BigUint64Array,r),fL=r=>ur(Float32Array,r),pL=r=>ur(Float64Array,r),mL=r=>ur(Uint8ClampedArray,r),cf=r=>(r.next(),r);function*Xn(r,t){const e=function*(i){yield i},n=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof xp?e(t):Vx(t)?t:e(t);return yield*cf(function*(i){let s=null;do s=i.next(yield ur(r,s));while(!s.done)}(n[Symbol.iterator]())),new r}const gL=r=>Xn(Int8Array,r),yL=r=>Xn(Int16Array,r),vL=r=>Xn(Int32Array,r),_L=r=>Xn(Uint8Array,r),bL=r=>Xn(Uint16Array,r),wL=r=>Xn(Uint32Array,r),xL=r=>Xn(Float32Array,r),SL=r=>Xn(Float64Array,r),TL=r=>Xn(Uint8ClampedArray,r);function mn(r,t){return br(this,arguments,function*(){if(JD(t))return yield Rt(yield Rt(yield*Ss(Bn(mn(r,yield Rt(t))))));const n=function(o){return br(this,arguments,function*(){yield yield Rt(yield Rt(o))})},i=function(o){return br(this,arguments,function*(){yield Rt(yield*Ss(Bn(cf(function*(a){let l=null;do l=a.next(yield l==null?void 0:l.value);while(!l.done)}(o[Symbol.iterator]())))))})},s=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof xp?n(t):Vx(t)?i(t):tL(t)?t:n(t);return yield Rt(yield*Ss(Bn(cf(function(o){return br(this,arguments,function*(){let a=null;do a=yield Rt(o.next(yield yield Rt(ur(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Rt(new r)})}const IL=r=>mn(Int8Array,r),EL=r=>mn(Int16Array,r),AL=r=>mn(Int32Array,r),ML=r=>mn(Uint8Array,r),CL=r=>mn(Uint16Array,r),OL=r=>mn(Uint32Array,r),PL=r=>mn(Float32Array,r),RL=r=>mn(Float64Array,r),FL=r=>mn(Uint8ClampedArray,r);function DL(r,t,e){if(r!==0){e=e.slice(0,t);for(let n=-1,i=e.length;++n0)do if(r[e]!==t[e])return!1;while(++eFo(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}const BL=Object.freeze(Object.defineProperty({__proto__:null,valueToString:Fo},Symbol.toStringTag,{value:"Module"}));function pr(r){if(typeof r=="bigint"&&(rNumber.MAX_SAFE_INTEGER))throw new TypeError(`${r} is not safe to convert to a number.`);return Number(r)}function $x(r,t){return pr(r/t)+pr(r%t)/pr(t)}const Gx=Symbol.for("isArrowBigNum");function gn(r,...t){return t.length===0?Object.setPrototypeOf(ur(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}gn.prototype[Gx]=!0;gn.prototype.toJSON=function(){return`"${Do(this)}"`};gn.prototype.valueOf=function(r){return Sp(this,r)};gn.prototype.toString=function(){return Do(this)};gn.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Sp(this);case"string":return Do(this);case"default":return Wx(this)}return Do(this)};function xo(...r){return gn.apply(this,r)}function So(...r){return gn.apply(this,r)}function $a(...r){return gn.apply(this,r)}Object.setPrototypeOf(xo.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(So.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf($a.prototype,Object.create(Uint32Array.prototype));Object.assign(xo.prototype,gn.prototype,{constructor:xo,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(So.prototype,gn.prototype,{constructor:So,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign($a.prototype,gn.prototype,{constructor:$a,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const UL=BigInt(4294967296)*BigInt(4294967296),kL=UL-BigInt(1);function Sp(r,t){const{buffer:e,byteOffset:n,byteLength:i,signed:s}=r,o=new BigUint64Array(e,n,i/8),a=s&&o.at(-1)&BigInt(1)<=0)return kh(r);t=t.slice();let n=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(Ct.prototype);class My extends Ct{constructor(){super(H.Null)}toString(){return"Null"}}Xx=Symbol.toStringTag;My[Xx]=(r=>r[Symbol.toStringTag]="Null")(My.prototype);class Cy extends Ct{constructor(t,e){super(H.Int),this.isSigned=t,this.bitWidth=e}get ArrayType(){switch(this.bitWidth){case 8:return this.isSigned?Int8Array:Uint8Array;case 16:return this.isSigned?Int16Array:Uint16Array;case 32:return this.isSigned?Int32Array:Uint32Array;case 64:return this.isSigned?BigInt64Array:BigUint64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`${this.isSigned?"I":"Ui"}nt${this.bitWidth}`}}Yx=Symbol.toStringTag;Cy[Yx]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))(Cy.prototype);class Oy extends Ct{constructor(t){super(H.Float),this.precision=t}get ArrayType(){switch(this.precision){case Dr.HALF:return Uint16Array;case Dr.SINGLE:return Float32Array;case Dr.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}qx=Symbol.toStringTag;Oy[qx]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(Oy.prototype);class Py extends Ct{constructor(){super(H.Binary)}toString(){return"Binary"}}Qx=Symbol.toStringTag;Py[Qx]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(Py.prototype);class Ry extends Ct{constructor(){super(H.LargeBinary)}toString(){return"LargeBinary"}}Zx=Symbol.toStringTag;Ry[Zx]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(Ry.prototype);class Fy extends Ct{constructor(){super(H.Utf8)}toString(){return"Utf8"}}Kx=Symbol.toStringTag;Fy[Kx]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(Fy.prototype);class Dy extends Ct{constructor(){super(H.LargeUtf8)}toString(){return"LargeUtf8"}}Jx=Symbol.toStringTag;Dy[Jx]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(Dy.prototype);class Ly extends Ct{constructor(){super(H.Bool)}toString(){return"Bool"}}tS=Symbol.toStringTag;Ly[tS]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(Ly.prototype);class Ny extends Ct{constructor(t,e,n=128){super(H.Decimal),this.scale=t,this.precision=e,this.bitWidth=n}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}eS=Symbol.toStringTag;Ny[eS]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(Ny.prototype);class By extends Ct{constructor(t){super(H.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${Bi[this.unit]}>`}get ArrayType(){return this.unit===Bi.DAY?Int32Array:BigInt64Array}}rS=Symbol.toStringTag;By[rS]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(By.prototype);class Uy extends Ct{constructor(t,e){super(H.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${te[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}nS=Symbol.toStringTag;Uy[nS]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(Uy.prototype);class ky extends Ct{constructor(t,e){super(H.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${te[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}iS=Symbol.toStringTag;ky[iS]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(ky.prototype);class zy extends Ct{constructor(t){super(H.Interval),this.unit=t}toString(){return`Interval<${As[this.unit]}>`}}sS=Symbol.toStringTag;zy[sS]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(zy.prototype);class Vy extends Ct{constructor(t){super(H.Duration),this.unit=t}toString(){return`Duration<${te[this.unit]}>`}}oS=Symbol.toStringTag;Vy[oS]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(Vy.prototype);class jy extends Ct{constructor(t){super(H.List),this.children=[t]}toString(){return`List<${this.valueType}>`}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}}aS=Symbol.toStringTag;jy[aS]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(jy.prototype);class hf extends Ct{constructor(t){super(H.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}}lS=Symbol.toStringTag;hf[lS]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(hf.prototype);class $y extends Ct{constructor(t,e,n){super(H.Union),this.mode=t,this.children=n,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((i,s,o)=>(i[s]=o)&&i||i,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}}uS=Symbol.toStringTag;$y[uS]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))($y.prototype);class Gy extends Ct{constructor(t){super(H.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}cS=Symbol.toStringTag;Gy[cS]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(Gy.prototype);class Wy extends Ct{constructor(t,e){super(H.FixedSizeList),this.listSize=t,this.children=[e]}get valueType(){return this.children[0].type}get valueField(){return this.children[0]}get ArrayType(){return this.valueType.ArrayType}toString(){return`FixedSizeList[${this.listSize}]<${this.valueType}>`}}hS=Symbol.toStringTag;Wy[hS]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(Wy.prototype);class Hy extends Ct{constructor(t,e=!1){var n,i,s;if(super(H.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((n=t==null?void 0:t.type)===null||n===void 0)&&n.children)){const o=(i=t==null?void 0:t.type)===null||i===void 0?void 0:i.children[0];o&&(o.name="key");const a=(s=t==null?void 0:t.type)===null||s===void 0?void 0:s.children[1];a&&(a.name="value")}}get keyType(){return this.children[0].type.children[0].type}get valueType(){return this.children[0].type.children[1].type}get childType(){return this.children[0].type}toString(){return`Map<{${this.children[0].type.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}}dS=Symbol.toStringTag;Hy[dS]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(Hy.prototype);const VL=(r=>()=>++r)(-1);class Xy extends Ct{constructor(t,e,n,i){super(H.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=i||!1,this.id=n==null?VL():pr(n)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}fS=Symbol.toStringTag;Xy[fS]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(Xy.prototype);function pS(r){const t=r;switch(r.typeId){case H.Decimal:return r.bitWidth/32;case H.Interval:return 1+t.unit;case H.FixedSizeList:return t.listSize;case H.FixedSizeBinary:return t.byteWidth;default:return 1}}class he{visitMany(t,...e){return t.map((n,i)=>this.visit(n,...e.map(s=>s[i])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return jL(this,t,e)}getVisitFnByTypeId(t,e=!0){return ao(this,t,e)}visitNull(t,...e){return null}visitBool(t,...e){return null}visitInt(t,...e){return null}visitFloat(t,...e){return null}visitUtf8(t,...e){return null}visitLargeUtf8(t,...e){return null}visitBinary(t,...e){return null}visitLargeBinary(t,...e){return null}visitFixedSizeBinary(t,...e){return null}visitDate(t,...e){return null}visitTimestamp(t,...e){return null}visitTime(t,...e){return null}visitDecimal(t,...e){return null}visitList(t,...e){return null}visitStruct(t,...e){return null}visitUnion(t,...e){return null}visitDictionary(t,...e){return null}visitInterval(t,...e){return null}visitDuration(t,...e){return null}visitFixedSizeList(t,...e){return null}visitMap(t,...e){return null}}function jL(r,t,e=!0){return typeof t=="number"?ao(r,t,e):typeof t=="string"&&t in H?ao(r,H[t],e):t&&t instanceof Ct?ao(r,Yy(t),e):t!=null&&t.type&&t.type instanceof Ct?ao(r,Yy(t.type),e):ao(r,H.NONE,e)}function ao(r,t,e=!0){let n=null;switch(t){case H.Null:n=r.visitNull;break;case H.Bool:n=r.visitBool;break;case H.Int:n=r.visitInt;break;case H.Int8:n=r.visitInt8||r.visitInt;break;case H.Int16:n=r.visitInt16||r.visitInt;break;case H.Int32:n=r.visitInt32||r.visitInt;break;case H.Int64:n=r.visitInt64||r.visitInt;break;case H.Uint8:n=r.visitUint8||r.visitInt;break;case H.Uint16:n=r.visitUint16||r.visitInt;break;case H.Uint32:n=r.visitUint32||r.visitInt;break;case H.Uint64:n=r.visitUint64||r.visitInt;break;case H.Float:n=r.visitFloat;break;case H.Float16:n=r.visitFloat16||r.visitFloat;break;case H.Float32:n=r.visitFloat32||r.visitFloat;break;case H.Float64:n=r.visitFloat64||r.visitFloat;break;case H.Utf8:n=r.visitUtf8;break;case H.LargeUtf8:n=r.visitLargeUtf8;break;case H.Binary:n=r.visitBinary;break;case H.LargeBinary:n=r.visitLargeBinary;break;case H.FixedSizeBinary:n=r.visitFixedSizeBinary;break;case H.Date:n=r.visitDate;break;case H.DateDay:n=r.visitDateDay||r.visitDate;break;case H.DateMillisecond:n=r.visitDateMillisecond||r.visitDate;break;case H.Timestamp:n=r.visitTimestamp;break;case H.TimestampSecond:n=r.visitTimestampSecond||r.visitTimestamp;break;case H.TimestampMillisecond:n=r.visitTimestampMillisecond||r.visitTimestamp;break;case H.TimestampMicrosecond:n=r.visitTimestampMicrosecond||r.visitTimestamp;break;case H.TimestampNanosecond:n=r.visitTimestampNanosecond||r.visitTimestamp;break;case H.Time:n=r.visitTime;break;case H.TimeSecond:n=r.visitTimeSecond||r.visitTime;break;case H.TimeMillisecond:n=r.visitTimeMillisecond||r.visitTime;break;case H.TimeMicrosecond:n=r.visitTimeMicrosecond||r.visitTime;break;case H.TimeNanosecond:n=r.visitTimeNanosecond||r.visitTime;break;case H.Decimal:n=r.visitDecimal;break;case H.List:n=r.visitList;break;case H.Struct:n=r.visitStruct;break;case H.Union:n=r.visitUnion;break;case H.DenseUnion:n=r.visitDenseUnion||r.visitUnion;break;case H.SparseUnion:n=r.visitSparseUnion||r.visitUnion;break;case H.Dictionary:n=r.visitDictionary;break;case H.Interval:n=r.visitInterval;break;case H.IntervalDayTime:n=r.visitIntervalDayTime||r.visitInterval;break;case H.IntervalYearMonth:n=r.visitIntervalYearMonth||r.visitInterval;break;case H.Duration:n=r.visitDuration;break;case H.DurationSecond:n=r.visitDurationSecond||r.visitDuration;break;case H.DurationMillisecond:n=r.visitDurationMillisecond||r.visitDuration;break;case H.DurationMicrosecond:n=r.visitDurationMicrosecond||r.visitDuration;break;case H.DurationNanosecond:n=r.visitDurationNanosecond||r.visitDuration;break;case H.FixedSizeList:n=r.visitFixedSizeList;break;case H.Map:n=r.visitMap;break}if(typeof n=="function")return n;if(!e)return()=>null;throw new Error(`Unrecognized type '${H[t]}'`)}function Yy(r){switch(r.typeId){case H.Null:return H.Null;case H.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?H.Int8:H.Uint8;case 16:return e?H.Int16:H.Uint16;case 32:return e?H.Int32:H.Uint32;case 64:return e?H.Int64:H.Uint64}return H.Int}case H.Float:switch(r.precision){case Dr.HALF:return H.Float16;case Dr.SINGLE:return H.Float32;case Dr.DOUBLE:return H.Float64}return H.Float;case H.Binary:return H.Binary;case H.LargeBinary:return H.LargeBinary;case H.Utf8:return H.Utf8;case H.LargeUtf8:return H.LargeUtf8;case H.Bool:return H.Bool;case H.Decimal:return H.Decimal;case H.Time:switch(r.unit){case te.SECOND:return H.TimeSecond;case te.MILLISECOND:return H.TimeMillisecond;case te.MICROSECOND:return H.TimeMicrosecond;case te.NANOSECOND:return H.TimeNanosecond}return H.Time;case H.Timestamp:switch(r.unit){case te.SECOND:return H.TimestampSecond;case te.MILLISECOND:return H.TimestampMillisecond;case te.MICROSECOND:return H.TimestampMicrosecond;case te.NANOSECOND:return H.TimestampNanosecond}return H.Timestamp;case H.Date:switch(r.unit){case Bi.DAY:return H.DateDay;case Bi.MILLISECOND:return H.DateMillisecond}return H.Date;case H.Interval:switch(r.unit){case As.DAY_TIME:return H.IntervalDayTime;case As.YEAR_MONTH:return H.IntervalYearMonth}return H.Interval;case H.Duration:switch(r.unit){case te.SECOND:return H.DurationSecond;case te.MILLISECOND:return H.DurationMillisecond;case te.MICROSECOND:return H.DurationMicrosecond;case te.NANOSECOND:return H.DurationNanosecond}return H.Duration;case H.Map:return H.Map;case H.List:return H.List;case H.Struct:return H.Struct;case H.Union:switch(r.mode){case jn.Dense:return H.DenseUnion;case jn.Sparse:return H.SparseUnion}return H.Union;case H.FixedSizeBinary:return H.FixedSizeBinary;case H.FixedSizeList:return H.FixedSizeList;case H.Dictionary:return H.Dictionary}throw new Error(`Unrecognized type '${H[r.typeId]}'`)}he.prototype.visitInt8=null;he.prototype.visitInt16=null;he.prototype.visitInt32=null;he.prototype.visitInt64=null;he.prototype.visitUint8=null;he.prototype.visitUint16=null;he.prototype.visitUint32=null;he.prototype.visitUint64=null;he.prototype.visitFloat16=null;he.prototype.visitFloat32=null;he.prototype.visitFloat64=null;he.prototype.visitDateDay=null;he.prototype.visitDateMillisecond=null;he.prototype.visitTimestampSecond=null;he.prototype.visitTimestampMillisecond=null;he.prototype.visitTimestampMicrosecond=null;he.prototype.visitTimestampNanosecond=null;he.prototype.visitTimeSecond=null;he.prototype.visitTimeMillisecond=null;he.prototype.visitTimeMicrosecond=null;he.prototype.visitTimeNanosecond=null;he.prototype.visitDenseUnion=null;he.prototype.visitSparseUnion=null;he.prototype.visitIntervalDayTime=null;he.prototype.visitIntervalYearMonth=null;he.prototype.visitDuration=null;he.prototype.visitDurationSecond=null;he.prototype.visitDurationMillisecond=null;he.prototype.visitDurationMicrosecond=null;he.prototype.visitDurationNanosecond=null;const mS=new Float64Array(1),Hs=new Uint32Array(mS.buffer);function Tp(r){const t=(r&31744)>>10,e=(r&1023)/1024,n=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return n*(e?Number.NaN:1/0);case 0:return n*(e?6103515625e-14*e:0)}return n*Math.pow(2,t-15)*(1+e)}function gS(r){if(r!==r)return 32256;mS[0]=r;const t=(Hs[1]&2147483648)>>16&65535;let e=Hs[1]&2146435072,n=0;return e>=1089470464?Hs[0]>0?e=31744:(e=(e&2080374784)>>16,n=(Hs[1]&1048575)>>10):e<=1056964608?(n=1048576+(Hs[1]&1048575),n=1048576+(n<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,n=(Hs[1]&1048575)+512>>10),t|e|n&65535}const $L=Object.freeze(Object.defineProperty({__proto__:null,float64ToUint16:gS,uint16ToFloat64:Tp},Symbol.toStringTag,{value:"Module"}));class Wt extends he{}function qt(r){return(t,e,n)=>{if(t.setValid(e,n!=null))return r(t,e,n)}}const GL=(r,t,e)=>{r[t]=Math.floor(e/864e5)},yS=(r,t,e,n)=>{if(e+1{const i=r+e;n?t[i>>3]|=1<>3]&=~(1<{r[t]=e},Ip=({values:r},t,e)=>{r[t]=e},vS=({values:r},t,e)=>{r[t]=gS(e)},HL=(r,t,e)=>{switch(r.type.precision){case Dr.HALF:return vS(r,t,e);case Dr.SINGLE:case Dr.DOUBLE:return Ip(r,t,e)}},_S=({values:r},t,e)=>{GL(r,t,e.valueOf())},bS=({values:r},t,e)=>{r[t]=BigInt(e)},XL=({stride:r,values:t},e,n)=>{t.set(n.subarray(0,r),r*e)},wS=({values:r,valueOffsets:t},e,n)=>yS(r,t,e,n),xS=({values:r,valueOffsets:t},e,n)=>yS(r,t,e,zx(n)),YL=(r,t,e)=>{r.type.unit===Bi.DAY?_S(r,t,e):bS(r,t,e)},SS=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},TS=({values:r},t,e)=>{r[t]=BigInt(e)},IS=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},ES=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},qL=(r,t,e)=>{switch(r.type.unit){case te.SECOND:return SS(r,t,e);case te.MILLISECOND:return TS(r,t,e);case te.MICROSECOND:return IS(r,t,e);case te.NANOSECOND:return ES(r,t,e)}},AS=({values:r},t,e)=>{r[t]=e},MS=({values:r},t,e)=>{r[t]=e},CS=({values:r},t,e)=>{r[t]=e},OS=({values:r},t,e)=>{r[t]=e},QL=(r,t,e)=>{switch(r.type.unit){case te.SECOND:return AS(r,t,e);case te.MILLISECOND:return MS(r,t,e);case te.MICROSECOND:return CS(r,t,e);case te.NANOSECOND:return OS(r,t,e)}},ZL=({values:r,stride:t},e,n)=>{r.set(n.subarray(0,t),t*e)},KL=(r,t,e)=>{const n=r.children[0],i=r.valueOffsets,s=$n.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=i[t],l=i[t+1];a{const n=r.children[0],{valueOffsets:i}=r,s=$n.getVisitFn(n);let{[t]:o,[t+1]:a}=i;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(n,o,u),++o>=a)break},tN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t[s]),eN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t.get(s)),rN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t.get(i.name)),nN=(r,t)=>(e,n,i,s)=>n&&e(n,r,t[i.name]),iN=(r,t,e)=>{const n=r.type.children.map(s=>$n.getVisitFn(s.type)),i=e instanceof Map?rN(t,e):e instanceof er?eN(t,e):Array.isArray(e)?tN(t,e):nN(t,e);r.type.children.forEach((s,o)=>i(n[o],r.children[o],s,o))},sN=(r,t,e)=>{r.type.mode===jn.Dense?PS(r,t,e):RS(r,t,e)},PS=(r,t,e)=>{const n=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[n];$n.visit(i,r.valueOffsets[t],e)},RS=(r,t,e)=>{const n=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[n];$n.visit(i,t,e)},oN=(r,t,e)=>{var n;(n=r.dictionary)===null||n===void 0||n.set(r.values[t],e)},aN=(r,t,e)=>{r.type.unit===As.DAY_TIME?FS(r,t,e):DS(r,t,e)},FS=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},DS=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},LS=({values:r},t,e)=>{r[t]=e},NS=({values:r},t,e)=>{r[t]=e},BS=({values:r},t,e)=>{r[t]=e},US=({values:r},t,e)=>{r[t]=e},lN=(r,t,e)=>{switch(r.type.unit){case te.SECOND:return LS(r,t,e);case te.MILLISECOND:return NS(r,t,e);case te.MICROSECOND:return BS(r,t,e);case te.NANOSECOND:return US(r,t,e)}},uN=(r,t,e)=>{const{stride:n}=r,i=r.children[0],s=$n.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=t*n;++o`${Fo(t)}: ${Fo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new cN(this[cn],this[To])}}class cN{constructor(t,e){this.childIndex=0,this.children=t.children,this.rowIndex=e,this.childFields=t.type.children,this.numChildren=this.childFields.length}[Symbol.iterator](){return this}next(){const t=this.childIndex;return te.name)}has(t,e){return t[cn].type.children.some(n=>n.name===e)}getOwnPropertyDescriptor(t,e){if(t[cn].type.children.some(n=>n.name===e))return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const n=t[cn].type.children.findIndex(i=>i.name===e);if(n!==-1){const i=on.visit(t[cn].children[n],t[To]);return Reflect.set(t,e,i),i}}set(t,e,n){const i=t[cn].type.children.findIndex(s=>s.name===e);return i!==-1?($n.visit(t[cn].children[i],t[To],n),Reflect.set(t,e,n)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,n):!1}}const dN=new hN;class Bt extends he{}function Ht(r){return(t,e)=>t.getValid(e)?r(t,e):null}const fN=(r,t)=>864e5*r[t],pN=(r,t)=>null,kS=(r,t,e)=>{if(e+1>=t.length)return null;const n=pr(t[e]),i=pr(t[e+1]);return r.subarray(n,i)},mN=({offset:r,values:t},e)=>{const n=r+e;return(t[n>>3]&1<fN(r,t),VS=({values:r},t)=>pr(r[t]),Vi=({stride:r,values:t},e)=>t[r*e],gN=({stride:r,values:t},e)=>Tp(t[r*e]),jS=({values:r},t)=>r[t],yN=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),$S=({values:r,valueOffsets:t},e)=>kS(r,t,e),GS=({values:r,valueOffsets:t},e)=>{const n=kS(r,t,e);return n!==null?ZD(n):null},vN=({values:r},t)=>r[t],_N=({type:r,values:t},e)=>r.precision!==Dr.HALF?t[e]:Tp(t[e]),bN=(r,t)=>r.type.unit===Bi.DAY?zS(r,t):VS(r,t),WS=({values:r},t)=>1e3*pr(r[t]),HS=({values:r},t)=>pr(r[t]),XS=({values:r},t)=>$x(r[t],BigInt(1e3)),YS=({values:r},t)=>$x(r[t],BigInt(1e6)),wN=(r,t)=>{switch(r.type.unit){case te.SECOND:return WS(r,t);case te.MILLISECOND:return HS(r,t);case te.MICROSECOND:return XS(r,t);case te.NANOSECOND:return YS(r,t)}},qS=({values:r},t)=>r[t],QS=({values:r},t)=>r[t],ZS=({values:r},t)=>r[t],KS=({values:r},t)=>r[t],xN=(r,t)=>{switch(r.type.unit){case te.SECOND:return qS(r,t);case te.MILLISECOND:return QS(r,t);case te.MICROSECOND:return ZS(r,t);case te.NANOSECOND:return KS(r,t)}},SN=({values:r,stride:t},e)=>hc.decimal(r.subarray(t*e,t*(e+1))),TN=(r,t)=>{const{valueOffsets:e,stride:n,children:i}=r,{[t*n]:s,[t*n+1]:o}=e,l=i[0].slice(s,o-s);return new er([l])},IN=(r,t)=>{const{valueOffsets:e,children:n}=r,{[t]:i,[t+1]:s}=e,o=n[0];return new Ap(o.slice(i,s-i))},EN=(r,t)=>new Ep(r,t),AN=(r,t)=>r.type.mode===jn.Dense?JS(r,t):tT(r,t),JS=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[e];return on.visit(n,r.valueOffsets[t])},tT=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[e];return on.visit(n,t)},MN=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},CN=(r,t)=>r.type.unit===As.DAY_TIME?eT(r,t):rT(r,t),eT=({values:r},t)=>r.subarray(2*t,2*(t+1)),rT=({values:r},t)=>{const e=r[t],n=new Int32Array(2);return n[0]=Math.trunc(e/12),n[1]=Math.trunc(e%12),n},nT=({values:r},t)=>r[t],iT=({values:r},t)=>r[t],sT=({values:r},t)=>r[t],oT=({values:r},t)=>r[t],ON=(r,t)=>{switch(r.type.unit){case te.SECOND:return nT(r,t);case te.MILLISECOND:return iT(r,t);case te.MICROSECOND:return sT(r,t);case te.NANOSECOND:return oT(r,t)}},PN=(r,t)=>{const{stride:e,children:n}=r,s=n[0].slice(t*e,e);return new er([s])};Bt.prototype.visitNull=Ht(pN);Bt.prototype.visitBool=Ht(mN);Bt.prototype.visitInt=Ht(vN);Bt.prototype.visitInt8=Ht(Vi);Bt.prototype.visitInt16=Ht(Vi);Bt.prototype.visitInt32=Ht(Vi);Bt.prototype.visitInt64=Ht(jS);Bt.prototype.visitUint8=Ht(Vi);Bt.prototype.visitUint16=Ht(Vi);Bt.prototype.visitUint32=Ht(Vi);Bt.prototype.visitUint64=Ht(jS);Bt.prototype.visitFloat=Ht(_N);Bt.prototype.visitFloat16=Ht(gN);Bt.prototype.visitFloat32=Ht(Vi);Bt.prototype.visitFloat64=Ht(Vi);Bt.prototype.visitUtf8=Ht(GS);Bt.prototype.visitLargeUtf8=Ht(GS);Bt.prototype.visitBinary=Ht($S);Bt.prototype.visitLargeBinary=Ht($S);Bt.prototype.visitFixedSizeBinary=Ht(yN);Bt.prototype.visitDate=Ht(bN);Bt.prototype.visitDateDay=Ht(zS);Bt.prototype.visitDateMillisecond=Ht(VS);Bt.prototype.visitTimestamp=Ht(wN);Bt.prototype.visitTimestampSecond=Ht(WS);Bt.prototype.visitTimestampMillisecond=Ht(HS);Bt.prototype.visitTimestampMicrosecond=Ht(XS);Bt.prototype.visitTimestampNanosecond=Ht(YS);Bt.prototype.visitTime=Ht(xN);Bt.prototype.visitTimeSecond=Ht(qS);Bt.prototype.visitTimeMillisecond=Ht(QS);Bt.prototype.visitTimeMicrosecond=Ht(ZS);Bt.prototype.visitTimeNanosecond=Ht(KS);Bt.prototype.visitDecimal=Ht(SN);Bt.prototype.visitList=Ht(TN);Bt.prototype.visitStruct=Ht(EN);Bt.prototype.visitUnion=Ht(AN);Bt.prototype.visitDenseUnion=Ht(JS);Bt.prototype.visitSparseUnion=Ht(tT);Bt.prototype.visitDictionary=Ht(MN);Bt.prototype.visitInterval=Ht(CN);Bt.prototype.visitIntervalDayTime=Ht(eT);Bt.prototype.visitIntervalYearMonth=Ht(rT);Bt.prototype.visitDuration=Ht(ON);Bt.prototype.visitDurationSecond=Ht(nT);Bt.prototype.visitDurationMillisecond=Ht(iT);Bt.prototype.visitDurationMicrosecond=Ht(sT);Bt.prototype.visitDurationNanosecond=Ht(oT);Bt.prototype.visitFixedSizeList=Ht(PN);Bt.prototype.visitMap=Ht(IN);const on=new Bt,lo=Symbol.for("keys"),Io=Symbol.for("vals"),uo=Symbol.for("kKeysAsStrings"),df=Symbol.for("_kKeysAsStrings");class Ap{constructor(t){return this[lo]=new er([t.children[0]]).memoize(),this[Io]=t.children[1],new Proxy(this,new FN)}get[uo](){return this[df]||(this[df]=Array.from(this[lo].toArray(),String))}[Symbol.iterator](){return new RN(this[lo],this[Io])}get size(){return this[lo].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[lo],e=this[Io],n={};for(let i=-1,s=t.length;++i`${Fo(t)}: ${Fo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class RN{constructor(t,e){this.keys=t,this.vals=e,this.keyIndex=0,this.numKeys=t.length}[Symbol.iterator](){return this}next(){const t=this.keyIndex;return t===this.numKeys?{done:!0,value:null}:(this.keyIndex++,{done:!1,value:[this.keys.get(t),on.visit(this.vals,t)]})}}class FN{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[uo]}has(t,e){return t[uo].includes(e)}getOwnPropertyDescriptor(t,e){if(t[uo].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const n=t[uo].indexOf(e);if(n!==-1){const i=on.visit(Reflect.get(t,Io),n);return Reflect.set(t,e,i),i}}set(t,e,n){const i=t[uo].indexOf(e);return i!==-1?($n.visit(Reflect.get(t,Io),i,n),Reflect.set(t,e,n)):Reflect.has(t,e)?Reflect.set(t,e,n):!1}}Object.defineProperties(Ap.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[lo]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Io]:{writable:!0,enumerable:!1,configurable:!1,value:null},[df]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let qy;function aT(r,t,e,n){const{length:i=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?i:e;return s<0&&(s=(s%i+i)%i),o<0&&(o=(o%i+i)%i),oi&&(o=i),n?n(r,s,o):[s,o]}const lT=(r,t)=>r<0?t+r:r,Qy=r=>r!==r;function Ds(r){if(typeof r!=="object"||r===null)return Qy(r)?Qy:e=>e===r;if(r instanceof Date){const e=r.valueOf();return n=>n instanceof Date?n.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?jx(r,e):!1:r instanceof Map?LN(r):Array.isArray(r)?DN(r):r instanceof er?NN(r):BN(r,!0)}function DN(r){const t=[];for(let e=-1,n=r.length;++e!1;const n=[];for(let i=-1,s=e.length;++i{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return UN(r,e);case Map:return Zy(r,e,e.keys());case Ap:case Ep:case Object:case void 0:return Zy(r,e,t||Object.keys(e))}return e instanceof er?kN(r,e):!1}}function UN(r,t){const e=r.length;if(t.length!==e)return!1;for(let n=-1;++n>n}function VN(r,t,e){return e?!!(r[t>>3]|=1<>3]&=~(1<0||e.byteLength>3):cT(new fc(e,r,t,null,Mp)).subarray(0,n)),i}return e}function cT(r){const t=[];let e=0,n=0,i=0;for(const o of r)o&&(i|=1<0)&&(t[e++]=i);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}class fc{constructor(t,e,n,i,s){this.bytes=t,this.length=n,this.context=i,this.get=s,this.bit=e%8,this.byteIndex=e>>3,this.byte=t[this.byteIndex++],this.index=0}next(){return this.index>3<<3,i=t+(t%8===0?0:8-t%8);return ju(r,t,i)+ju(r,n,e)+hT(r,i>>3,n-i>>3)}function hT(r,t,e){let n=0,i=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:i+e;for(;o-i>=4;)n+=Zl(s.getUint32(i)),i+=4;for(;o-i>=2;)n+=Zl(s.getUint16(i)),i+=2;for(;o-i>=1;)n+=Zl(s.getUint8(i)),i+=1;return n}function Zl(r){let t=Math.trunc(r);return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),(t+(t>>>4)&252645135)*16843009>>>24}const jN=Object.freeze(Object.defineProperty({__proto__:null,BitIterator:fc,getBit:uT,getBool:Mp,packBools:cT,popcnt_array:hT,popcnt_bit_range:ju,popcnt_uint32:Zl,setBool:VN,truncateBitmap:ff},Symbol.toStringTag,{value:"Module"})),$N=-1;class Ga{get typeId(){return this.type.typeId}get ArrayType(){return this.type.ArrayType}get buffers(){return[this.valueOffsets,this.values,this.nullBitmap,this.typeIds]}get nullable(){if(this._nullCount!==0){const{type:t}=this;return Ct.isSparseUnion(t)?this.children.some(e=>e.nullable):Ct.isDenseUnion(t)?this.children.some(e=>e.nullable):this.nullBitmap&&this.nullBitmap.byteLength>0}return!0}get byteLength(){let t=0;const{valueOffsets:e,values:n,nullBitmap:i,typeIds:s}=this;return e&&(t+=e.byteLength),n&&(t+=n.byteLength),i&&(t+=i.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(Ct.isUnion(this.type))return this.children.reduce((n,i)=>n+i.nullCount,0);let t=this._nullCount,e;return t<=$N&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-ju(e,this.offset,this.offset+this.length)),t}constructor(t,e,n,i,s,o=[],a){this.type=t,this.children=o,this.dictionary=a,this.offset=Math.floor(Math.max(e||0,0)),this.length=Math.floor(Math.max(n||0,0)),this._nullCount=Math.floor(Math.max(i||0,-1));let l;s instanceof Ga?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=pS(t),s&&((l=s[0])&&(this.valueOffsets=l),(l=s[1])&&(this.values=l),(l=s[2])&&(this.nullBitmap=l),(l=s[3])&&(this.typeIds=l)))}getValid(t){const{type:e}=this;if(Ct.isUnion(e)){const n=e,i=this.children[n.typeIdToChildIndex[this.typeIds[t]]],s=n.mode===jn.Dense?this.valueOffsets[t]:t;return i.getValid(s)}if(this.nullable&&this.nullCount>0){const n=this.offset+t;return(this.nullBitmap[n>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(ff(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];n=(h&u)!==0,s[c]=e?h|u:h&~u}return n!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,n=this.length,i=this._nullCount,s=this,o=this.children){return new Ga(t,e,n,i,s,o,this.dictionary)}slice(t,e){const{stride:n,typeId:i,children:s}=this,o=+(this._nullCount===0)-1,a=i===16?n:1,l=this._sliceBuffers(t,e,n,i);return this.clone(this.type,this.offset+t,e,o,l,s.length===0||this.valueOffsets?s:this._sliceChildren(s,a*t,a*e))}_changeLengthAndBackfillNullBitmap(t){if(this.typeId===H.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:n}=this,i=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);i[e>>3]=(1<0&&i.set(ff(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[si.VALIDITY]=i,this.clone(this.type,0,t,n+(t-e),s)}_sliceBuffers(t,e,n,i){let s;const{buffers:o}=this;return(s=o[si.TYPE])&&(o[si.TYPE]=s.subarray(t,t+e)),(s=o[si.OFFSET])&&(o[si.OFFSET]=s.subarray(t,t+e+1))||(s=o[si.DATA])&&(o[si.DATA]=i===6?s:s.subarray(n*t,n*(t+e))),o}_sliceChildren(t,e,n){return t.map(i=>i.slice(e,n))}}Ga.prototype.children=Object.freeze([]);class Ky{constructor(t=0,e){this.numChunks=t,this.getChunkIterator=e,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndext.nullable)}function WN(r){return r.reduce((t,e)=>t+e.nullCount,0)}function HN(r){return r.reduce((t,e,n)=>(t[n+1]=t[n]+e.length,t),new Uint32Array(r.length+1))}function XN(r,t,e,n){const i=[];for(let s=-1,o=r.length;++s=n)break;if(e>=l+u)continue;if(l>=e&&l+u<=n){i.push(a);continue}const c=Math.max(0,e-l),h=Math.min(n-l,u);i.push(a.slice(c,h-c))}return i.length===0&&i.push(r[0].slice(0,0)),i}function Cp(r,t,e,n){let i=0,s=0,o=t.length-1;do{if(i>=o-1)return e0?0:-1}function ZN(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let n=0;for(const i of new fc(e,r.offset+(t||0),r.length,e,Mp)){if(!i)return n;++n}return-1}function Kt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case H.Union:break;case H.Dictionary:break;default:return ZN(r,e)}const n=on.getVisitFn(r),i=Ds(t);for(let s=(e||0)-1,o=r.length;++s{const i=r.data[n];return i.values.subarray(0,i.length)[Symbol.iterator]()});let e=0;return new Ky(r.data.length,n=>{const s=r.data[n].length,o=r.slice(e,e+s);return e+=s,new KN(o)})}class KN{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof Ga)))throw new TypeError("Vector constructor expects an Array of Data instances.");const o=(e=s[0])===null||e===void 0?void 0:e.type;switch(s.length){case 0:this._offsets=[0];break;case 1:{const{get:a,set:l,indexOf:u}=mT[o.typeId],c=s[0];this.isValid=h=>dT(c,h),this.get=h=>a(c,h),this.set=(h,f)=>l(c,h,f),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,gT[o.typeId]),this._offsets=HN(s);break}this.data=s,this.type=o,this.stride=pS(o),this.numChildren=(i=(n=o.children)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return GN(this.data)}get nullCount(){return WN(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${H[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(lT(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return JN.visit(this)}concat(...t){return new er(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new er(aT(this,t,e,({data:n,_offsets:i},s,o)=>XN(n,i,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:n,stride:i,ArrayType:s}=this;switch(t.typeId){case H.Int:case H.Float:case H.Decimal:case H.Time:case H.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,n*i);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*i),o.offset),o.offset+=l*i,o),{array:new s(n*i),offset:0}).array}}return[...this]}toString(){return`[${[...this].join(",")}]`}getChild(t){var e;return this.getChildAt((e=this.type.children)===null||e===void 0?void 0:e.findIndex(n=>n.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return Ct.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(Ct.isDictionary(this.type)){const t=new $u(this.data[0].dictionary),e=this.data.map(n=>{const i=n.clone();return i.dictionary=t,i});return new er(e)}return new $u(this)}unmemoize(){if(Ct.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(n=>{const i=n.clone();return i.dictionary=t,i});return new er(e)}return this}}pT=Symbol.toStringTag;er[pT]=(r=>{r.type=Ct.prototype,r.data=[],r.length=0,r.stride=1,r.numChildren=0,r._offsets=new Uint32Array([0]),r[Symbol.isConcatSpreadable]=!0;const t=Object.keys(H).map(e=>H[e]).filter(e=>typeof e=="number"&&e!==H.NONE);for(const e of t){const n=on.getVisitFnByTypeId(e),i=$n.getVisitFnByTypeId(e),s=tv.getVisitFnByTypeId(e);mT[e]={get:n,set:i,indexOf:s},gT[e]=Object.create(r,{isValid:{value:Jy(dT)},get:{value:Jy(on.getVisitFnByTypeId(e))},set:{value:YN($n.getVisitFnByTypeId(e))},indexOf:{value:qN(tv.getVisitFnByTypeId(e))}})}return"Vector"})(er.prototype);class $u extends er{constructor(t){super(t.data);const e=this.get,n=this.set,i=this.slice,s=new Array(this.length);Object.defineProperty(this,"get",{value(o){const a=s[o];if(a!==void 0)return a;const l=e.call(this,o);return s[o]=l,l}}),Object.defineProperty(this,"set",{value(o,a){n.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new $u(i.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new er(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}const tB=65536;function po(r){return r<0&&(r=4294967295+r+1),`0x${r.toString(16)}`}const Lo=8,Op=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8];class Pp{constructor(t){this.buffer=t}high(){return this.buffer[1]}low(){return this.buffer[0]}_times(t){const e=new Uint32Array([this.buffer[1]>>>16,this.buffer[1]&65535,this.buffer[0]>>>16,this.buffer[0]&65535]),n=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let i=e[3]*n[3];this.buffer[0]=i&65535;let s=i>>>16;return i=e[2]*n[3],s+=i,i=e[3]*n[2]>>>0,s+=i,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*n[3]+e[2]*n[2]+e[3]*n[1],this.buffer[1]+=e[0]*n[3]+e[1]*n[2]+e[2]*n[1]+e[3]*n[0]<<16,this}_plus(t){const e=this.buffer[0]+t.buffer[0]>>>0;this.buffer[1]+=t.buffer[1],e>>0&&++this.buffer[1],this.buffer[0]=e}lessThan(t){return this.buffer[1]>>0,e[2]=this.buffer[2]+t.buffer[2]>>>0,e[1]=this.buffer[1]+t.buffer[1]>>>0,e[0]=this.buffer[0]+t.buffer[0]>>>0,e[0]>>0&&++e[1],e[1]>>0&&++e[2],e[2]>>0&&++e[3],this.buffer[3]=e[3],this.buffer[2]=e[2],this.buffer[1]=e[1],this.buffer[0]=e[0],this}hex(){return`${po(this.buffer[3])} ${po(this.buffer[2])} ${po(this.buffer[1])} ${po(this.buffer[0])}`}static multiply(t,e){return new En(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new En(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return En.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return En.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const n=t.startsWith("-"),i=t.length,s=new En(e);for(let o=n?1:0;othis.compareFields(n,e[i]))}compareFields(t,e){return t===e||e instanceof t.constructor&&t.name===e.name&&t.nullable===e.nullable&&this.visit(t.type,e.type)}}function gr(r,t){return t instanceof r.constructor}function Ls(r,t){return r===t||gr(r,t)}function mi(r,t){return r===t||gr(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function pc(r,t){return r===t||gr(r,t)&&r.precision===t.precision}function rB(r,t){return r===t||gr(r,t)&&r.byteWidth===t.byteWidth}function Rp(r,t){return r===t||gr(r,t)&&r.unit===t.unit}function rl(r,t){return r===t||gr(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function nl(r,t){return r===t||gr(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function nB(r,t){return r===t||gr(r,t)&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}function iB(r,t){return r===t||gr(r,t)&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}function Fp(r,t){return r===t||gr(r,t)&&r.mode===t.mode&&r.typeIds.every((e,n)=>e===t.typeIds[n])&&Gn.compareManyFields(r.children,t.children)}function sB(r,t){return r===t||gr(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&Gn.visit(r.indices,t.indices)&&Gn.visit(r.dictionary,t.dictionary)}function Dp(r,t){return r===t||gr(r,t)&&r.unit===t.unit}function il(r,t){return r===t||gr(r,t)&&r.unit===t.unit}function oB(r,t){return r===t||gr(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}function aB(r,t){return r===t||gr(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&Gn.compareManyFields(r.children,t.children)}zt.prototype.visitNull=Ls;zt.prototype.visitBool=Ls;zt.prototype.visitInt=mi;zt.prototype.visitInt8=mi;zt.prototype.visitInt16=mi;zt.prototype.visitInt32=mi;zt.prototype.visitInt64=mi;zt.prototype.visitUint8=mi;zt.prototype.visitUint16=mi;zt.prototype.visitUint32=mi;zt.prototype.visitUint64=mi;zt.prototype.visitFloat=pc;zt.prototype.visitFloat16=pc;zt.prototype.visitFloat32=pc;zt.prototype.visitFloat64=pc;zt.prototype.visitUtf8=Ls;zt.prototype.visitLargeUtf8=Ls;zt.prototype.visitBinary=Ls;zt.prototype.visitLargeBinary=Ls;zt.prototype.visitFixedSizeBinary=rB;zt.prototype.visitDate=Rp;zt.prototype.visitDateDay=Rp;zt.prototype.visitDateMillisecond=Rp;zt.prototype.visitTimestamp=rl;zt.prototype.visitTimestampSecond=rl;zt.prototype.visitTimestampMillisecond=rl;zt.prototype.visitTimestampMicrosecond=rl;zt.prototype.visitTimestampNanosecond=rl;zt.prototype.visitTime=nl;zt.prototype.visitTimeSecond=nl;zt.prototype.visitTimeMillisecond=nl;zt.prototype.visitTimeMicrosecond=nl;zt.prototype.visitTimeNanosecond=nl;zt.prototype.visitDecimal=Ls;zt.prototype.visitList=nB;zt.prototype.visitStruct=iB;zt.prototype.visitUnion=Fp;zt.prototype.visitDenseUnion=Fp;zt.prototype.visitSparseUnion=Fp;zt.prototype.visitDictionary=sB;zt.prototype.visitInterval=Dp;zt.prototype.visitIntervalDayTime=Dp;zt.prototype.visitIntervalYearMonth=Dp;zt.prototype.visitDuration=il;zt.prototype.visitDurationSecond=il;zt.prototype.visitDurationMillisecond=il;zt.prototype.visitDurationMicrosecond=il;zt.prototype.visitDurationNanosecond=il;zt.prototype.visitFixedSizeList=oB;zt.prototype.visitMap=aB;const Gn=new zt;function lB(r,t){return Gn.compareSchemas(r,t)}function uB(r,t){return Gn.compareFields(r,t)}function cB(r,t){return Gn.visit(r,t)}const ev=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zL),eB),jN),$L),LL),zN),BL),{compareSchemas:lB,compareFields:uB,compareTypes:cB}),yT=6048e5,hB=864e5,rv=Symbol.for("constructDateFrom");function ui(r,t){return typeof r=="function"?r(t):r&&typeof r=="object"&&rv in r?r[rv](t):r instanceof Date?new r.constructor(t):new Date(t)}function an(r,t){return ui(t||r,r)}let dB={};function mc(){return dB}function Wa(r,t){var a,l,u,c;const e=mc(),n=(t==null?void 0:t.weekStartsOn)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.weekStartsOn)??e.weekStartsOn??((c=(u=e.locale)==null?void 0:u.options)==null?void 0:c.weekStartsOn)??0,i=an(r,t==null?void 0:t.in),s=i.getDay(),o=(s=s.getTime()?n+1:e.getTime()>=a.getTime()?n:n-1}function nv(r){const t=an(r),e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),+r-+e}function fB(r,...t){const e=ui.bind(null,t.find(n=>typeof n=="object"));return t.map(e)}function iv(r,t){const e=an(r,t==null?void 0:t.in);return e.setHours(0,0,0,0),e}function pB(r,t,e){const[n,i]=fB(e==null?void 0:e.in,r,t),s=iv(n),o=iv(i),a=+s-nv(s),l=+o-nv(o);return Math.round((a-l)/hB)}function mB(r,t){const e=vT(r,t),n=ui(r,0);return n.setFullYear(e,0,4),n.setHours(0,0,0,0),Gu(n)}function gB(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function yB(r){return!(!gB(r)&&typeof r!="number"||isNaN(+an(r)))}function vB(r,t){const e=an(r,t==null?void 0:t.in);return e.setFullYear(e.getFullYear(),0,1),e.setHours(0,0,0,0),e}const _B={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},bB=(r,t,e)=>{let n;const i=_B[r];return typeof i=="string"?n=i:t===1?n=i.one:n=i.other.replace("{{count}}",t.toString()),e!=null&&e.addSuffix?e.comparison&&e.comparison>0?"in "+n:n+" ago":n};function zh(r){return(t={})=>{const e=t.width?String(t.width):r.defaultWidth;return r.formats[e]||r.formats[r.defaultWidth]}}const wB={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},xB={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},SB={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},TB={date:zh({formats:wB,defaultWidth:"full"}),time:zh({formats:xB,defaultWidth:"full"}),dateTime:zh({formats:SB,defaultWidth:"full"})},IB={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},EB=(r,t,e,n)=>IB[r];function sa(r){return(t,e)=>{const n=e!=null&&e.context?String(e.context):"standalone";let i;if(n==="formatting"&&r.formattingValues){const o=r.defaultFormattingWidth||r.defaultWidth,a=e!=null&&e.width?String(e.width):o;i=r.formattingValues[a]||r.formattingValues[o]}else{const o=r.defaultWidth,a=e!=null&&e.width?String(e.width):r.defaultWidth;i=r.values[a]||r.values[o]}const s=r.argumentCallback?r.argumentCallback(t):t;return i[s]}}const AB={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},MB={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},CB={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},OB={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},PB={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},RB={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},FB=(r,t)=>{const e=Number(r),n=e%100;if(n>20||n<10)switch(n%10){case 1:return e+"st";case 2:return e+"nd";case 3:return e+"rd"}return e+"th"},DB={ordinalNumber:FB,era:sa({values:AB,defaultWidth:"wide"}),quarter:sa({values:MB,defaultWidth:"wide",argumentCallback:r=>r-1}),month:sa({values:CB,defaultWidth:"wide"}),day:sa({values:OB,defaultWidth:"wide"}),dayPeriod:sa({values:PB,defaultWidth:"wide",formattingValues:RB,defaultFormattingWidth:"wide"})};function oa(r){return(t,e={})=>{const n=e.width,i=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],s=t.match(i);if(!s)return null;const o=s[0],a=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],l=Array.isArray(a)?NB(a,h=>h.test(o)):LB(a,h=>h.test(o));let u;u=r.valueCallback?r.valueCallback(l):l,u=e.valueCallback?e.valueCallback(u):u;const c=t.slice(o.length);return{value:u,rest:c}}}function LB(r,t){for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)&&t(r[e]))return e}function NB(r,t){for(let e=0;e{const n=t.match(r.matchPattern);if(!n)return null;const i=n[0],s=t.match(r.parsePattern);if(!s)return null;let o=r.valueCallback?r.valueCallback(s[0]):s[0];o=e.valueCallback?e.valueCallback(o):o;const a=t.slice(i.length);return{value:o,rest:a}}}const UB=/^(\d+)(th|st|nd|rd)?/i,kB=/\d+/i,zB={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},VB={any:[/^b/i,/^(a|c)/i]},jB={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},$B={any:[/1/i,/2/i,/3/i,/4/i]},GB={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},WB={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},HB={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},XB={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},YB={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},qB={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},QB={ordinalNumber:BB({matchPattern:UB,parsePattern:kB,valueCallback:r=>parseInt(r,10)}),era:oa({matchPatterns:zB,defaultMatchWidth:"wide",parsePatterns:VB,defaultParseWidth:"any"}),quarter:oa({matchPatterns:jB,defaultMatchWidth:"wide",parsePatterns:$B,defaultParseWidth:"any",valueCallback:r=>r+1}),month:oa({matchPatterns:GB,defaultMatchWidth:"wide",parsePatterns:WB,defaultParseWidth:"any"}),day:oa({matchPatterns:HB,defaultMatchWidth:"wide",parsePatterns:XB,defaultParseWidth:"any"}),dayPeriod:oa({matchPatterns:YB,defaultMatchWidth:"any",parsePatterns:qB,defaultParseWidth:"any"})},ZB={code:"en-US",formatDistance:bB,formatLong:TB,formatRelative:EB,localize:DB,match:QB,options:{weekStartsOn:0,firstWeekContainsDate:1}};function KB(r,t){const e=an(r,t==null?void 0:t.in);return pB(e,vB(e))+1}function JB(r,t){const e=an(r,t==null?void 0:t.in),n=+Gu(e)-+mB(e);return Math.round(n/yT)+1}function _T(r,t){var c,h,f,d;const e=an(r,t==null?void 0:t.in),n=e.getFullYear(),i=mc(),s=(t==null?void 0:t.firstWeekContainsDate)??((h=(c=t==null?void 0:t.locale)==null?void 0:c.options)==null?void 0:h.firstWeekContainsDate)??i.firstWeekContainsDate??((d=(f=i.locale)==null?void 0:f.options)==null?void 0:d.firstWeekContainsDate)??1,o=ui((t==null?void 0:t.in)||r,0);o.setFullYear(n+1,0,s),o.setHours(0,0,0,0);const a=Wa(o,t),l=ui((t==null?void 0:t.in)||r,0);l.setFullYear(n,0,s),l.setHours(0,0,0,0);const u=Wa(l,t);return+e>=+a?n+1:+e>=+u?n:n-1}function tU(r,t){var a,l,u,c;const e=mc(),n=(t==null?void 0:t.firstWeekContainsDate)??((l=(a=t==null?void 0:t.locale)==null?void 0:a.options)==null?void 0:l.firstWeekContainsDate)??e.firstWeekContainsDate??((c=(u=e.locale)==null?void 0:u.options)==null?void 0:c.firstWeekContainsDate)??1,i=_T(r,t),s=ui((t==null?void 0:t.in)||r,0);return s.setFullYear(i,0,n),s.setHours(0,0,0,0),Wa(s,t)}function eU(r,t){const e=an(r,t==null?void 0:t.in),n=+Wa(e,t)-+tU(e,t);return Math.round(n/yT)+1}function we(r,t){const e=r<0?"-":"",n=Math.abs(r).toString().padStart(t,"0");return e+n}const wi={y(r,t){const e=r.getFullYear(),n=e>0?e:1-e;return we(t==="yy"?n%100:n,t.length)},M(r,t){const e=r.getMonth();return t==="M"?String(e+1):we(e+1,2)},d(r,t){return we(r.getDate(),t.length)},a(r,t){const e=r.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return e.toUpperCase();case"aaa":return e;case"aaaaa":return e[0];case"aaaa":default:return e==="am"?"a.m.":"p.m."}},h(r,t){return we(r.getHours()%12||12,t.length)},H(r,t){return we(r.getHours(),t.length)},m(r,t){return we(r.getMinutes(),t.length)},s(r,t){return we(r.getSeconds(),t.length)},S(r,t){const e=t.length,n=r.getMilliseconds(),i=Math.trunc(n*Math.pow(10,e-3));return we(i,t.length)}},Xs={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},sv={G:function(r,t,e){const n=r.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return e.era(n,{width:"abbreviated"});case"GGGGG":return e.era(n,{width:"narrow"});case"GGGG":default:return e.era(n,{width:"wide"})}},y:function(r,t,e){if(t==="yo"){const n=r.getFullYear(),i=n>0?n:1-n;return e.ordinalNumber(i,{unit:"year"})}return wi.y(r,t)},Y:function(r,t,e,n){const i=_T(r,n),s=i>0?i:1-i;if(t==="YY"){const o=s%100;return we(o,2)}return t==="Yo"?e.ordinalNumber(s,{unit:"year"}):we(s,t.length)},R:function(r,t){const e=vT(r);return we(e,t.length)},u:function(r,t){const e=r.getFullYear();return we(e,t.length)},Q:function(r,t,e){const n=Math.ceil((r.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return we(n,2);case"Qo":return e.ordinalNumber(n,{unit:"quarter"});case"QQQ":return e.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return e.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return e.quarter(n,{width:"wide",context:"formatting"})}},q:function(r,t,e){const n=Math.ceil((r.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return we(n,2);case"qo":return e.ordinalNumber(n,{unit:"quarter"});case"qqq":return e.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return e.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return e.quarter(n,{width:"wide",context:"standalone"})}},M:function(r,t,e){const n=r.getMonth();switch(t){case"M":case"MM":return wi.M(r,t);case"Mo":return e.ordinalNumber(n+1,{unit:"month"});case"MMM":return e.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return e.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return e.month(n,{width:"wide",context:"formatting"})}},L:function(r,t,e){const n=r.getMonth();switch(t){case"L":return String(n+1);case"LL":return we(n+1,2);case"Lo":return e.ordinalNumber(n+1,{unit:"month"});case"LLL":return e.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return e.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return e.month(n,{width:"wide",context:"standalone"})}},w:function(r,t,e,n){const i=eU(r,n);return t==="wo"?e.ordinalNumber(i,{unit:"week"}):we(i,t.length)},I:function(r,t,e){const n=JB(r);return t==="Io"?e.ordinalNumber(n,{unit:"week"}):we(n,t.length)},d:function(r,t,e){return t==="do"?e.ordinalNumber(r.getDate(),{unit:"date"}):wi.d(r,t)},D:function(r,t,e){const n=KB(r);return t==="Do"?e.ordinalNumber(n,{unit:"dayOfYear"}):we(n,t.length)},E:function(r,t,e){const n=r.getDay();switch(t){case"E":case"EE":case"EEE":return e.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return e.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return e.day(n,{width:"short",context:"formatting"});case"EEEE":default:return e.day(n,{width:"wide",context:"formatting"})}},e:function(r,t,e,n){const i=r.getDay(),s=(i-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(s);case"ee":return we(s,2);case"eo":return e.ordinalNumber(s,{unit:"day"});case"eee":return e.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return e.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return e.day(i,{width:"short",context:"formatting"});case"eeee":default:return e.day(i,{width:"wide",context:"formatting"})}},c:function(r,t,e,n){const i=r.getDay(),s=(i-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(s);case"cc":return we(s,t.length);case"co":return e.ordinalNumber(s,{unit:"day"});case"ccc":return e.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return e.day(i,{width:"narrow",context:"standalone"});case"cccccc":return e.day(i,{width:"short",context:"standalone"});case"cccc":default:return e.day(i,{width:"wide",context:"standalone"})}},i:function(r,t,e){const n=r.getDay(),i=n===0?7:n;switch(t){case"i":return String(i);case"ii":return we(i,t.length);case"io":return e.ordinalNumber(i,{unit:"day"});case"iii":return e.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return e.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return e.day(n,{width:"short",context:"formatting"});case"iiii":default:return e.day(n,{width:"wide",context:"formatting"})}},a:function(r,t,e){const i=r.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return e.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return e.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(r,t,e){const n=r.getHours();let i;switch(n===12?i=Xs.noon:n===0?i=Xs.midnight:i=n/12>=1?"pm":"am",t){case"b":case"bb":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return e.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return e.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(r,t,e){const n=r.getHours();let i;switch(n>=17?i=Xs.evening:n>=12?i=Xs.afternoon:n>=4?i=Xs.morning:i=Xs.night,t){case"B":case"BB":case"BBB":return e.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return e.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return e.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(r,t,e){if(t==="ho"){let n=r.getHours()%12;return n===0&&(n=12),e.ordinalNumber(n,{unit:"hour"})}return wi.h(r,t)},H:function(r,t,e){return t==="Ho"?e.ordinalNumber(r.getHours(),{unit:"hour"}):wi.H(r,t)},K:function(r,t,e){const n=r.getHours()%12;return t==="Ko"?e.ordinalNumber(n,{unit:"hour"}):we(n,t.length)},k:function(r,t,e){let n=r.getHours();return n===0&&(n=24),t==="ko"?e.ordinalNumber(n,{unit:"hour"}):we(n,t.length)},m:function(r,t,e){return t==="mo"?e.ordinalNumber(r.getMinutes(),{unit:"minute"}):wi.m(r,t)},s:function(r,t,e){return t==="so"?e.ordinalNumber(r.getSeconds(),{unit:"second"}):wi.s(r,t)},S:function(r,t){return wi.S(r,t)},X:function(r,t,e){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return av(n);case"XXXX":case"XX":return hs(n);case"XXXXX":case"XXX":default:return hs(n,":")}},x:function(r,t,e){const n=r.getTimezoneOffset();switch(t){case"x":return av(n);case"xxxx":case"xx":return hs(n);case"xxxxx":case"xxx":default:return hs(n,":")}},O:function(r,t,e){const n=r.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+ov(n,":");case"OOOO":default:return"GMT"+hs(n,":")}},z:function(r,t,e){const n=r.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+ov(n,":");case"zzzz":default:return"GMT"+hs(n,":")}},t:function(r,t,e){const n=Math.trunc(+r/1e3);return we(n,t.length)},T:function(r,t,e){return we(+r,t.length)}};function ov(r,t=""){const e=r>0?"-":"+",n=Math.abs(r),i=Math.trunc(n/60),s=n%60;return s===0?e+String(i):e+String(i)+t+we(s,2)}function av(r,t){return r%60===0?(r>0?"-":"+")+we(Math.abs(r)/60,2):hs(r,t)}function hs(r,t=""){const e=r>0?"-":"+",n=Math.abs(r),i=we(Math.trunc(n/60),2),s=we(n%60,2);return e+i+t+s}const lv=(r,t)=>{switch(r){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},bT=(r,t)=>{switch(r){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},rU=(r,t)=>{const e=r.match(/(P+)(p+)?/)||[],n=e[1],i=e[2];if(!i)return lv(r,t);let s;switch(n){case"P":s=t.dateTime({width:"short"});break;case"PP":s=t.dateTime({width:"medium"});break;case"PPP":s=t.dateTime({width:"long"});break;case"PPPP":default:s=t.dateTime({width:"full"});break}return s.replace("{{date}}",lv(n,t)).replace("{{time}}",bT(i,t))},nU={p:bT,P:rU},iU=/^D+$/,sU=/^Y+$/,oU=["D","DD","YY","YYYY"];function aU(r){return iU.test(r)}function lU(r){return sU.test(r)}function uU(r,t,e){const n=cU(r,t,e);if(console.warn(n),oU.includes(r))throw new RangeError(n)}function cU(r,t,e){const n=r[0]==="Y"?"years":"days of the month";return`Use \`${r.toLowerCase()}\` instead of \`${r}\` (in \`${t}\`) for formatting ${n} to the input \`${e}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const hU=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,dU=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,fU=/^'([^]*?)'?$/,pU=/''/g,mU=/[a-zA-Z]/;function wT(r,t,e){var c,h,f,d;const n=mc(),i=n.locale??ZB,s=n.firstWeekContainsDate??((h=(c=n.locale)==null?void 0:c.options)==null?void 0:h.firstWeekContainsDate)??1,o=n.weekStartsOn??((d=(f=n.locale)==null?void 0:f.options)==null?void 0:d.weekStartsOn)??0,a=an(r,e==null?void 0:e.in);if(!yB(a))throw new RangeError("Invalid time value");let l=t.match(dU).map(m=>{const g=m[0];if(g==="p"||g==="P"){const p=nU[g];return p(m,i.formatLong)}return m}).join("").match(hU).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const g=m[0];if(g==="'")return{isToken:!1,value:gU(m)};if(sv[g])return{isToken:!0,value:m};if(g.match(mU))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:m}});i.localize.preprocessor&&(l=i.localize.preprocessor(a,l));const u={firstWeekContainsDate:s,weekStartsOn:o,locale:i};return l.map(m=>{if(!m.isToken)return m.value;const g=m.value;(lU(g)||aU(g))&&uU(g,t,String(r));const p=sv[g[0]];return p(a,g,i.localize,u)}).join("")}function gU(r){const t=r.match(fU);return t?t[1].replace(pU,"'"):r}function yU(r,t){return an(r*1e3,t==null?void 0:t.in)}function vU(r,t){const e=_U(t)?new t(0):ui(t,0);return e.setFullYear(r.getFullYear(),r.getMonth(),r.getDate()),e.setHours(r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()),e}function _U(r){var t;return typeof r=="function"&&((t=r.prototype)==null?void 0:t.constructor)===r}function bU(r,t){let e=r.length;switch("string"){case"string":{for(;e>0&&r[e-1]===t;)e--;break}}return r.substring(0,e)}function Tr(r){return r==null}function wU(r){return r!=null}async function xT(){if(typeof window<"u"&&window!==null)return"browser";try{const r=await Ei(()=>import("./__vite-browser-external-FmFgRqLi.js"),[]);return typeof r<"u"&&r.versions!=null&&r.versions.node!=null?"node":"unknown"}catch{return"unknown"}}function xU(r){return Tr(r)?!1:Ct.isInt(r.type)&&!ST(r)||SU(r)}function SU(r){return Tr(r)?!1:Ct.isInt(r.type)&&r.type.isSigned===!1}function TU(r){return Tr(r)?!1:Ct.isFloat(r.type)??!1}function IU(r){return Tr(r)?!1:Ct.isDecimal(r.type)}function EU(r){return Tr(r)?!1:Ct.isBool(r.type)}function AU(r){return Tr(r)?!1:Ct.isDuration(r.type)}function ST(r){return Tr(r)?!1:Ct.isInt(r.type)&&r.metadata.get("ARROW:extension:name")==="period"}function MU(r){return Tr(r)?!1:Ct.isTimestamp(r.type)}function CU(r){return Tr(r)?!1:Ct.isDate(r.type)}function OU(r){return Tr(r)?!1:Ct.isTime(r.type)}function PU(r){return Tr(r)?!1:Ct.isList(r.type)||Ct.isFixedSizeList(r.type)}function RU(r){return Tr(r)?!1:Ct.isStruct(r.type)||Ct.isMap(r.type)}function FU(r){return Tr(r)?!1:Ct.isStruct(r.type)&&r.metadata.get("ARROW:extension:name")==="interval"||Ct.isInterval(r.type)}function DU(r,t){let e;if(t===te.MILLISECOND)e=1e3;else if(t===te.MICROSECOND)e=1e3*1e3;else if(t===te.NANOSECOND)e=1e3*1e3*1e3;else return Number(r);return typeof r=="bigint"&&!Number.isSafeInteger(Number(r))?Number(r/BigInt(e)):Number(r)/e}function LU(r,t){var n;const e=DU(r,((n=t==null?void 0:t.type)==null?void 0:n.unit)??te.SECOND);return yU(e)}function NU(r,t){const e=LU(r,t);return wT(e,e.getMilliseconds()===0?"HH:mm:ss":"HH:mm:ss.SSS")}function BU(r){const t="yyyy-MM-dd";return r instanceof Date||typeof r=="number"&&Number.isFinite(r)?wT(r,t):(console.warn(`Unsupported date value: ${r}`),String(r))}function UU(r,t){var i;if(!(r instanceof Date||typeof r=="number"&&Number.isFinite(r)))return console.warn(`Unsupported datetime value: ${r}`),null;let e;const n=(i=t==null?void 0:t.type)==null?void 0:i.timezone;return typeof r=="number"?n?e=new Fr(r,n):e=new Fr(r):n?e=new Fr(r,n):e=new Fr(r),vU(e,Date)}function kU(r,t){var a;const e=((a=t==null?void 0:t.type)==null?void 0:a.scale)||0;let n=ev.bigNumToString(new ev.BN(r)).padStart(e,"0");if(e===0)return n;let i="";n.startsWith("-")&&(i="-",n=n.slice(1));const s=n.slice(0,-e)||"0",o=bU(n.slice(-e),"0")||"";return`${i}${s}${o?`.${o}`:""}`}function zU(r){const t=r[0],e=r[1],n=[];return t!==0&&n.push(`${t} year${t>1?"s":""}`),e!==0&&n.push(`${e} month${e>1?"s":""}`),n.length?n.join(" "):"0 months"}function VU(r,t){var n,i,s,o;if(Ct.isInterval(t==null?void 0:t.type))return zU(r);const e=t&&t.metadata.get("ARROW:extension:name");if(e&&e==="pandas.interval"){const a=JSON.parse(t.metadata.get("ARROW:extension:metadata")),{closed:l}=a,u=r.toJSON(),c=l==="both"||l==="left"?"[":"(",h=l==="both"||l==="right"?"]":")",f=pf(u.left,(i=(n=t.type)==null?void 0:n.children)==null?void 0:i[0]),d=pf(u.right,(o=(s=t.type)==null?void 0:s.children)==null?void 0:o[1]);return`${c+f}, ${d+h}`}return String(r)}function jU(r,t){return(t==null?void 0:t.type)instanceof hf?JSON.parse(JSON.stringify(r,(e,n)=>{if(wU(n))return typeof n=="bigint"?Number(n):n})):JSON.parse(JSON.stringify(r,(e,n)=>typeof n=="bigint"?Number(n):n))}function pf(r,t){if(Tr(r))return null;const e=r instanceof Date||Number.isFinite(r);if(e&&CU(t))return BU(r);if(typeof r=="bigint"&&OU(t))return NU(Number(r),t);if(e&&MU(t))return UU(r,t);if(ST(t))throw new Error("Period type is not supported yet");if(FU(t))return VU(r,t);if(AU(t))throw new Error("Duration type is not supported yet");return IU(t)?kU(r,t):TU(t)&&Number.isFinite(r)||xU(t)?r:RU(t)||PU(t)?jU(r,t):EU(t)?!!r:String(r)}function uv(r){return((r.toArray()||[]).map(n=>n.toJSON())||[]).map(n=>(r.schema.fields.forEach(i=>n[i.name]=pf(n[i.name],i)),n))}var Ha=(r=>(r.ORIGIN_PRIVATE_FS="origin-private-fs",r.NODE_FS="node-fs",r))(Ha||{});async function TT(r){const t=M1(r,{logger:!1});let e,n;const i=await xT();if(i==="browser"){if(typeof t.bundles>"u"){const{getBundles:l}=await Ei(async()=>{const{getBundles:u}=await import("./default-browser-BrgSDbLD.js");return{getBundles:u}},[]);t.bundles=await l()}n=await Iy(await t.bundles),e=new Worker(n.mainWorker)}else if(i==="node"){if(typeof t.bundles>"u"){const{getBundles:c}=await Ei(async()=>{const{getBundles:h}=await import("./default-node-BIhtlSJe.js");return{getBundles:h}},__vite__mapDeps([0,1,2]));t.bundles=await c()}n=await Iy(await t.bundles);let l=n.mainWorker;l.startsWith("/@fs/")&&(l=l.replace("/@fs/","file://"));const u=await Ei(()=>import("./index-Cp8iQ_hy.js"),[]);e=new u.default(l,{type:"module"})}else throw new Error(`Unsupported environment: ${i}`);let s;t.logger===!0?s=new Bx:t.logger===!1?s=new PD:s=t.logger;const o=new UD(s,e);if(await o.instantiate(n.mainModule,n.pthreadWorker),t.storage)switch(t.storage.type){case Ha.ORIGIN_PRIVATE_FS:{try{let l=t.storage.path;l.startsWith("/")&&(l=l.slice(1)),await o.open({path:`opfs://${l}`,accessMode:t.storage.accessMode})}catch(l){throw await o.terminate(),await e.terminate(),l}break}case Ha.NODE_FS:{try{await o.open({path:t.storage.path,accessMode:t.storage.accessMode,useDirectIO:!0})}catch(l){throw await o.terminate(),await e.terminate(),l}break}}const a=await o.connect();return{worker:e,db:o,conn:a,query:async(l,u=[])=>{if(!u||u.length===0){const d=await a.query(l);return uv(d)}const c=await a.prepare(l),h=await c.query(...u),f=uv(h);return c.close(),f},close:async()=>{await a.close(),await o.terminate(),await e.terminate()}}}async function $U(r,t){await(await r).conn.send("BEGIN TRANSACTION");try{const e=await t(r);return await(await r).conn.send("COMMIT"),e}catch(e){throw await(await r).conn.send("ROLLBACK"),e}}async function GU(r,t,e){await(await r).conn.send(`SAVEPOINT ${t}`);try{const n=await e(r);return await(await r).conn.send(`RELEASE SAVEPOINT ${t}`),n}catch(n){throw await(await r).conn.send(`ROLLBACK TO SAVEPOINT ${t}`),n}}const St=Symbol.for("drizzle:entityKind");function lt(r,t){if(!r||typeof r!="object")return!1;if(r instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,St))throw new Error(`Class "${t.name??""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let e=Object.getPrototypeOf(r).constructor;if(e)for(;e;){if(St in e&&e[St]===t[St])return!0;e=Object.getPrototypeOf(e)}return!1}var bv;bv=St;class rr{constructor(t,e){W(this,"name");W(this,"keyAsName");W(this,"primary");W(this,"notNull");W(this,"default");W(this,"defaultFn");W(this,"onUpdateFn");W(this,"hasDefault");W(this,"isUnique");W(this,"uniqueName");W(this,"uniqueType");W(this,"dataType");W(this,"columnType");W(this,"enumValues");W(this,"generated");W(this,"generatedIdentity");W(this,"config");this.table=t,this.config=e,this.name=e.name,this.keyAsName=e.keyAsName,this.notNull=e.notNull,this.default=e.default,this.defaultFn=e.defaultFn,this.onUpdateFn=e.onUpdateFn,this.hasDefault=e.hasDefault,this.primary=e.primaryKey,this.isUnique=e.isUnique,this.uniqueName=e.uniqueName,this.uniqueType=e.uniqueType,this.dataType=e.dataType,this.columnType=e.columnType,this.generated=e.generated,this.generatedIdentity=e.generatedIdentity}mapFromDriverValue(t){return t}mapToDriverValue(t){return t}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}W(rr,bv,"Column");const Eo=Symbol.for("drizzle:Name");function WU(r,t){return`${r[Eo]}_${t.join("_")}_unique`}var wv,xv;class Lr extends(xv=rr,wv=St,xv){constructor(t,e){e.uniqueName||(e.uniqueName=WU(t,[e.name])),super(t,e),this.table=t}}W(Lr,wv,"PgColumn");const cv=Symbol.for("drizzle:isPgEnum");function HU(r){return!!r&&typeof r=="function"&&cv in r&&r[cv]===!0}var Sv;Sv=St;class Nr{constructor(t,e,n,i=!1){this._={brand:"Subquery",sql:t,selectedFields:e,alias:n,isWith:i}}}W(Nr,Sv,"Subquery");var Tv,Iv;class Lp extends(Iv=Nr,Tv=St,Iv){}W(Lp,Tv,"WithSubquery");const Ur={startActiveSpan(r,t){return t()}},Qe=Symbol.for("drizzle:ViewBaseConfig"),Kl=Symbol.for("drizzle:Schema"),mf=Symbol.for("drizzle:Columns"),hv=Symbol.for("drizzle:ExtraConfigColumns"),Vh=Symbol.for("drizzle:OriginalName"),jh=Symbol.for("drizzle:BaseName"),Wu=Symbol.for("drizzle:IsAlias"),dv=Symbol.for("drizzle:ExtraConfigBuilder"),XU=Symbol.for("drizzle:IsDrizzleTable");var Ev,Av,Mv,Cv,Ov,Pv,Rv,Fv,Dv,Lv;Lv=St,Dv=Eo,Fv=Vh,Rv=Kl,Pv=mf,Ov=hv,Cv=jh,Mv=Wu,Av=XU,Ev=dv;class It{constructor(t,e,n){W(this,Dv);W(this,Fv);W(this,Rv);W(this,Pv);W(this,Ov);W(this,Cv);W(this,Mv,!1);W(this,Av,!0);W(this,Ev);this[Eo]=this[Vh]=t,this[Kl]=e,this[jh]=n}}W(It,Lv,"Table"),W(It,"Symbol",{Name:Eo,Schema:Kl,OriginalName:Vh,Columns:mf,ExtraConfigColumns:hv,BaseName:jh,IsAlias:Wu,ExtraConfigBuilder:dv});function vs(r){return r[Eo]}function Xa(r){return`${r[Kl]??"public"}.${r[Eo]}`}function IT(r){return r!=null&&typeof r.getSQL=="function"}function YU(r){var e;const t={sql:"",params:[]};for(const n of r)t.sql+=n.sql,t.params.push(...n.params),(e=n.typings)!=null&&e.length&&(t.typings||(t.typings=[]),t.typings.push(...n.typings));return t}var Nv;Nv=St;class Ze{constructor(t){W(this,"value");this.value=Array.isArray(t)?t:[t]}getSQL(){return new Pt([this])}}W(Ze,Nv,"StringChunk");var Bv;Bv=St;const ps=class ps{constructor(t){W(this,"decoder",ET);W(this,"shouldInlineParams",!1);this.queryChunks=t}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return Ur.startActiveSpan("drizzle.buildSQL",e=>{const n=this.buildQueryFromSourceParams(this.queryChunks,t);return e==null||e.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(t,e){const n=Object.assign({},e,{inlineParams:e.inlineParams||this.shouldInlineParams,paramStartIndex:e.paramStartIndex||{value:0}}),{casing:i,escapeName:s,escapeParam:o,prepareTyping:a,inlineParams:l,paramStartIndex:u}=n;return YU(t.map(c=>{var h;if(lt(c,Ze))return{sql:c.value.join(""),params:[]};if(lt(c,Hu))return{sql:s(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){const f=[new Ze("(")];for(const[d,m]of c.entries())f.push(m),dr},AT={mapToDriverValue:r=>r};({...ET,...AT});var kv;kv=St;class ci{constructor(t,e=AT){W(this,"brand");this.value=t,this.encoder=e}getSQL(){return new Pt([this])}}W(ci,kv,"Param");function Y(r,...t){const e=[];(t.length>0||r.length>0&&r[0]!=="")&&e.push(new Ze(r[0]));for(const[n,i]of t.entries())e.push(i,new Ze(r[n+1]));return new Pt(e)}(r=>{function t(){return new Pt([])}r.empty=t;function e(l){return new Pt(l)}r.fromList=e;function n(l){return new Pt([new Ze(l)])}r.raw=n;function i(l,u){const c=[];for(const[h,f]of l.entries())h>0&&u!==void 0&&c.push(u),c.push(f);return new Pt(c)}r.join=i;function s(l){return new Hu(l)}r.identifier=s;function o(l){return new Ms(l)}r.placeholder=o;function a(l,u){return new ci(l,u)}r.param=a})(Y||(Y={}));(r=>{var e;e=St;const n=class n{constructor(s,o){W(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=o}getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}};W(n,e,"SQL.Aliased");let t=n;r.Aliased=t})(Pt||(Pt={}));var zv;zv=St;class Ms{constructor(t){this.name=t}getSQL(){return new Pt([this])}}W(Ms,zv,"Placeholder");function fv(r,t){return r.map(e=>{if(lt(e,Ms)){if(!(e.name in t))throw new Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(lt(e,ci)&<(e.value,Ms)){if(!(e.value.name in t))throw new Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(t[e.value.name])}return e})}const QU=Symbol.for("drizzle:IsDrizzleView");var Vv,jv,$v;$v=St,jv=Qe,Vv=QU;class ji{constructor({name:t,schema:e,selectedFields:n,query:i}){W(this,jv);W(this,Vv,!0);this[Qe]={name:t,originalName:t,schema:e,selectedFields:n,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Pt([this])}}W(ji,$v,"View");rr.prototype.getSQL=function(){return new Pt([this])};It.prototype.getSQL=function(){return new Pt([this])};Nr.prototype.getSQL=function(){return new Pt([this])};var Gv;Gv=St;class Ya{constructor(t){this.table=t}get(t,e){return e==="table"?this.table:t[e]}}W(Ya,Gv,"ColumnAliasProxyHandler");var Wv;Wv=St;class gc{constructor(t,e){this.alias=t,this.replaceOriginalName=e}get(t,e){if(e===It.Symbol.IsAlias)return!0;if(e===It.Symbol.Name)return this.alias;if(this.replaceOriginalName&&e===It.Symbol.OriginalName)return this.alias;if(e===Qe)return{...t[Qe],name:this.alias,isAlias:!0};if(e===It.Symbol.Columns){const i=t[It.Symbol.Columns];if(!i)return i;const s={};return Object.keys(i).map(o=>{s[o]=new Proxy(i[o],new Ya(new Proxy(t,this)))}),s}const n=t[e];return lt(n,rr)?new Proxy(n,new Ya(new Proxy(t,this))):n}}W(gc,Wv,"TableAliasProxyHandler");function $h(r,t){return new Proxy(r,new gc(t,!1))}function ei(r,t){return new Proxy(r,new Ya(new Proxy(r.table,new gc(t,!1))))}function MT(r,t){return new Pt.Aliased(Xu(r.sql,t),r.fieldAlias)}function Xu(r,t){return Y.join(r.queryChunks.map(e=>lt(e,rr)?ei(e,t):lt(e,Pt)?Xu(e,t):lt(e,Pt.Aliased)?MT(e,t):e))}var Hv,Xv;class Np extends(Xv=Error,Hv=St,Xv){constructor({message:t,cause:e}){super(t),this.name="DrizzleError",this.cause=e}}W(Np,Hv,"DrizzleError");var Yv,qv;class CT extends(qv=Np,Yv=St,qv){constructor(){super({message:"Rollback"})}}W(CT,Yv,"TransactionRollbackError");function Sr(r,t){return qU(t)&&!IT(r)&&!lt(r,ci)&&!lt(r,Ms)&&!lt(r,rr)&&!lt(r,It)&&!lt(r,ji)?new ci(r,t):r}const OT=(r,t)=>Y`${r} = ${Sr(t,r)}`,ZU=(r,t)=>Y`${r} <> ${Sr(t,r)}`;function gf(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Pt(t):new Pt([new Ze("("),Y.join(t,new Ze(" and ")),new Ze(")")])}function KU(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Pt(t):new Pt([new Ze("("),Y.join(t,new Ze(" or ")),new Ze(")")])}function JU(r){return Y`not ${r}`}const tk=(r,t)=>Y`${r} > ${Sr(t,r)}`,ek=(r,t)=>Y`${r} >= ${Sr(t,r)}`,rk=(r,t)=>Y`${r} < ${Sr(t,r)}`,nk=(r,t)=>Y`${r} <= ${Sr(t,r)}`;function ik(r,t){return Array.isArray(t)?t.length===0?Y`false`:Y`${r} in ${t.map(e=>Sr(e,r))}`:Y`${r} in ${Sr(t,r)}`}function sk(r,t){return Array.isArray(t)?t.length===0?Y`true`:Y`${r} not in ${t.map(e=>Sr(e,r))}`:Y`${r} not in ${Sr(t,r)}`}function ok(r){return Y`${r} is null`}function ak(r){return Y`${r} is not null`}function lk(r){return Y`exists ${r}`}function uk(r){return Y`not exists ${r}`}function ck(r,t,e){return Y`${r} between ${Sr(t,r)} and ${Sr(e,r)}`}function hk(r,t,e){return Y`${r} not between ${Sr(t,r)} and ${Sr(e,r)}`}function dk(r,t){return Y`${r} like ${t}`}function fk(r,t){return Y`${r} not like ${t}`}function pk(r,t){return Y`${r} ilike ${t}`}function mk(r,t){return Y`${r} not ilike ${t}`}function gk(r){return Y`${r} asc`}function yk(r){return Y`${r} desc`}var Qv;Qv=St;class PT{write(t){console.log(t)}}W(PT,Qv,"ConsoleLogWriter");var Zv;Zv=St;class RT{constructor(t){W(this,"writer");this.writer=(t==null?void 0:t.writer)??new PT}logQuery(t,e){const n=e.map(s=>{try{return JSON.stringify(s)}catch{return String(s)}}),i=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${t}${i}`)}}W(RT,Zv,"DefaultLogger");var Kv;Kv=St;class FT{logQuery(){}}W(FT,Kv,"NoopLogger");var Jv,t_;t_=St,Jv=Symbol.toStringTag;class $i{constructor(){W(this,Jv,"QueryPromise")}catch(t){return this.then(void 0,t)}finally(t){return this.then(e=>(t==null||t(),e),e=>{throw t==null||t(),e})}then(t,e){return this.execute().then(t,e)}}W($i,t_,"QueryPromise");function Cs(r,t){return Object.entries(r).reduce((e,[n,i])=>{if(typeof n!="string")return e;const s=t?[...t,n]:[n];return lt(i,rr)||lt(i,Pt)||lt(i,Pt.Aliased)?e.push({path:s,field:i}):lt(i,It)?e.push(...Cs(i[It.Symbol.Columns],s)):e.push(...Cs(i,s)),e},[])}function Bp(r,t){const e=Object.keys(r),n=Object.keys(t);if(e.length!==n.length)return!1;for(const[i,s]of e.entries())if(s!==n[i])return!1;return!0}function DT(r,t){const e=Object.entries(t).filter(([,n])=>n!==void 0).map(([n,i])=>lt(i,Pt)||lt(i,rr)?[n,i]:[n,new ci(i,r[It.Symbol.Columns][n])]);if(e.length===0)throw new Error("No values to set");return Object.fromEntries(e)}function vk(r,t){for(const e of t)for(const n of Object.getOwnPropertyNames(e.prototype))n!=="constructor"&&Object.defineProperty(r.prototype,n,Object.getOwnPropertyDescriptor(e.prototype,n)||Object.create(null))}function _k(r){return r[It.Symbol.Columns]}function fs(r){return lt(r,Nr)?r._.alias:lt(r,ji)?r[Qe].name:lt(r,Pt)?void 0:r[It.Symbol.IsAlias]?r[It.Symbol.Name]:r[It.Symbol.BaseName]}function bk(r){if(typeof r!="object"||r===null||r.constructor.name!=="Object")return!1;if("logger"in r){const t=typeof r.logger;return!(t!=="boolean"&&(t!=="object"||typeof r.logger.logQuery!="function")&&t!=="undefined")}if("schema"in r){const t=typeof r.schema;return!(t!=="object"&&t!=="undefined")}if("casing"in r){const t=typeof r.casing;return!(t!=="string"&&t!=="undefined")}if("mode"in r)return!(r.mode!=="default"||r.mode!=="planetscale"||r.mode!==void 0);if("connection"in r){const t=typeof r.connection;return!(t!=="string"&&t!=="object"&&t!=="undefined")}if("client"in r){const t=typeof r.client;return!(t!=="object"&&t!=="function"&&t!=="undefined")}return Object.keys(r).length===0}var e_,r_;class LT extends(r_=Lr,e_=St,r_){getSQLType(){return"date"}mapFromDriverValue(t){return new Date(t)}mapToDriverValue(t){return t.toISOString()}}W(LT,e_,"PgDate");var n_,i_;class NT extends(i_=Lr,n_=St,i_){getSQLType(){return"date"}}W(NT,n_,"PgDateString");var s_,o_;class BT extends(o_=Lr,s_=St,o_){constructor(t,e){super(t,e)}getSQLType(){return"json"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}W(BT,s_,"PgJson");var a_,l_;class UT extends(l_=Lr,a_=St,l_){constructor(t,e){super(t,e)}getSQLType(){return"jsonb"}mapToDriverValue(t){return JSON.stringify(t)}mapFromDriverValue(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}W(UT,a_,"PgJsonb");var u_,c_;class kT extends(c_=Lr,u_=St,c_){constructor(e,n){super(e,n);W(this,"precision");W(this,"scale");this.precision=n.precision,this.scale=n.scale}mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}}W(kT,u_,"PgNumeric");var h_,d_;class zT extends(d_=Lr,h_=St,d_){constructor(e,n){super(e,n);W(this,"withTimezone");W(this,"precision");this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}W(zT,h_,"PgTime");var f_,p_;class VT extends(p_=Lr,f_=St,p_){constructor(e,n){super(e,n);W(this,"withTimezone");W(this,"precision");W(this,"mapFromDriverValue",e=>new Date(this.withTimezone?e:e+"+0000"));W(this,"mapToDriverValue",e=>e.toISOString());this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}}W(VT,f_,"PgTimestamp");var m_,g_;class jT extends(g_=Lr,m_=St,g_){constructor(e,n){super(e,n);W(this,"withTimezone");W(this,"precision");this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}W(jT,m_,"PgTimestampString");var y_,v_;class $T extends(v_=Lr,y_=St,v_){getSQLType(){return"uuid"}}W($T,y_,"PgUUID");const pv=Symbol.for("drizzle:PgInlineForeignKeys"),mv=Symbol.for("drizzle:EnableRLS");var __,b_,w_,x_,S_,T_;class Xr extends(T_=It,S_=St,x_=pv,w_=mv,b_=It.Symbol.ExtraConfigBuilder,__=It.Symbol.ExtraConfigColumns,T_){constructor(){super(...arguments);W(this,x_,[]);W(this,w_,!1);W(this,b_);W(this,__,{})}}W(Xr,S_,"PgTable"),W(Xr,"Symbol",Object.assign({},It.Symbol,{InlineForeignKeys:pv,EnableRLS:mv}));var I_;I_=St;class GT{constructor(t,e){W(this,"columns");W(this,"name");this.columns=t,this.name=e}build(t){return new WT(t,this.columns,this.name)}}W(GT,I_,"PgPrimaryKeyBuilder");var E_;E_=St;class WT{constructor(t,e,n){W(this,"columns");W(this,"name");this.table=t,this.columns=e,this.name=n}getName(){return this.name??`${this.table[Xr.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}}W(WT,E_,"PgPrimaryKey");var A_;A_=St;class Up{constructor(t,e,n){W(this,"referencedTableName");W(this,"fieldName");this.sourceTable=t,this.referencedTable=e,this.relationName=n,this.referencedTableName=e[It.Symbol.Name]}}W(Up,A_,"Relation");var M_;M_=St;class HT{constructor(t,e){this.table=t,this.config=e}}W(HT,M_,"Relations");var C_,O_;const Qu=class Qu extends(O_=Up,C_=St,O_){constructor(t,e,n,i){super(t,e,n==null?void 0:n.relationName),this.config=n,this.isNullable=i}withFieldName(t){const e=new Qu(this.sourceTable,this.referencedTable,this.config,this.isNullable);return e.fieldName=t,e}};W(Qu,C_,"One");let Os=Qu;var P_,R_;const Zu=class Zu extends(R_=Up,P_=St,R_){constructor(t,e,n){super(t,e,n==null?void 0:n.relationName),this.config=n}withFieldName(t){const e=new Zu(this.sourceTable,this.referencedTable,this.config);return e.fieldName=t,e}};W(Zu,P_,"Many");let Yu=Zu;function wk(){return{and:gf,between:ck,eq:OT,exists:lk,gt:tk,gte:ek,ilike:pk,inArray:ik,isNull:ok,isNotNull:ak,like:dk,lt:rk,lte:nk,ne:ZU,not:JU,notBetween:hk,notExists:uk,notLike:fk,notIlike:mk,notInArray:sk,or:KU,sql:Y}}function xk(){return{sql:Y,asc:gk,desc:yk}}function Sk(r,t){var s;Object.keys(r).length===1&&"default"in r&&!lt(r.default,It)&&(r=r.default);const e={},n={},i={};for(const[o,a]of Object.entries(r))if(lt(a,It)){const l=Xa(a),u=n[l];e[l]=o,i[o]={tsName:o,dbName:a[It.Symbol.Name],schema:a[It.Symbol.Schema],columns:a[It.Symbol.Columns],relations:(u==null?void 0:u.relations)??{},primaryKey:(u==null?void 0:u.primaryKey)??[]};for(const h of Object.values(a[It.Symbol.Columns]))h.primary&&i[o].primaryKey.push(h);const c=(s=a[It.Symbol.ExtraConfigBuilder])==null?void 0:s.call(a,a[It.Symbol.ExtraConfigColumns]);if(c)for(const h of Object.values(c))lt(h,GT)&&i[o].primaryKey.push(...h.columns)}else if(lt(a,HT)){const l=Xa(a.table),u=e[l],c=a.config(t(a.table));let h;for(const[f,d]of Object.entries(c))if(u){const m=i[u];m.relations[f]=d}else l in n||(n[l]={relations:{},primaryKey:h}),n[l].relations[f]=d}return{tables:i,tableNamesMap:e}}function Tk(r){return function(e,n){return new Os(r,e,n,(n==null?void 0:n.fields.reduce((i,s)=>i&&s.notNull,!0))??!1)}}function Ik(r){return function(e,n){return new Yu(r,e,n)}}function Ek(r,t,e){if(lt(e,Os)&&e.config)return{fields:e.config.fields,references:e.config.references};const n=t[Xa(e.referencedTable)];if(!n)throw new Error(`Table "${e.referencedTable[It.Symbol.Name]}" not found in schema`);const i=r[n];if(!i)throw new Error(`Table "${n}" not found in schema`);const s=e.sourceTable,o=t[Xa(s)];if(!o)throw new Error(`Table "${s[It.Symbol.Name]}" not found in schema`);const a=[];for(const l of Object.values(i.relations))(e.relationName&&e!==l&&l.relationName===e.relationName||!e.relationName&&l.referencedTable===e.sourceTable)&&a.push(l);if(a.length>1)throw e.relationName?new Error(`There are multiple relations with name "${e.relationName}" in table "${n}"`):new Error(`There are multiple relations between "${n}" and "${e.sourceTable[It.Symbol.Name]}". Please specify relation name`);if(a[0]&<(a[0],Os)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${o}.${e.fieldName}"`)}function Ak(r){return{one:Tk(r),many:Ik(r)}}function yf(r,t,e,n,i=s=>s){const s={};for(const[o,a]of n.entries())if(a.isJson){const l=t.relations[a.tsKey],u=e[o],c=typeof u=="string"?JSON.parse(u):u;s[a.tsKey]=lt(l,Os)?c&&yf(r,r[a.relationTableTsKey],c,a.selection,i):c.map(h=>yf(r,r[a.relationTableTsKey],h,a.selection,i))}else{const l=i(e[o]),u=a.field;let c;lt(u,rr)?c=u:lt(u,Pt)?c=u.decoder:c=u.sql.decoder,s[a.tsKey]=l===null?null:c.mapFromDriverValue(l)}return s}var F_;F_=St;const Ku=class Ku{constructor(t){W(this,"config");this.config={...t}}get(t,e){if(e==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(e===Qe)return{...t[Qe],selectedFields:new Proxy(t[Qe].selectedFields,this)};if(typeof e=="symbol")return t[e];const i=(lt(t,Nr)?t._.selectedFields:lt(t,ji)?t[Qe].selectedFields:t)[e];if(lt(i,Pt.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;const s=i.clone();return s.isSelectionField=!0,s}if(lt(i,Pt)){if(this.config.sqlBehavior==="sql")return i;throw new Error(`You tried to reference "${e}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return lt(i,rr)?this.config.alias?new Proxy(i,new Ya(new Proxy(i.table,new gc(this.config.alias,this.config.replaceOriginalName??!1)))):i:typeof i!="object"||i===null?i:new Proxy(i,new Ku(this.config))}};W(Ku,F_,"SelectionProxyHandler");let or=Ku;var D_,L_;class vf extends(L_=$i,D_=St,L_){constructor(e,n,i,s){super();W(this,"config");W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=n,this.dialect=i,this.config={table:e,withList:s}}where(e){return this.config.where=e,this}returning(e=this.config.table[It.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Cs(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0))}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new or({alias:vs(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}W(vf,D_,"PgDelete");function Mk(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function Ck(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,n,i)=>{const s=i===0?n.toLowerCase():`${n[0].toUpperCase()}${n.slice(1)}`;return e+s},"")}function Ok(r){return r}var N_;N_=St;class XT{constructor(t){W(this,"cache",{});W(this,"cachedTables",{});W(this,"convert");this.convert=t==="snake_case"?Mk:t==="camelCase"?Ck:Ok}getColumnCasing(t){if(!t.keyAsName)return t.name;const e=t.table[It.Symbol.Schema]??"public",n=t.table[It.Symbol.OriginalName],i=`${e}.${n}.${t.name}`;return this.cache[i]||this.cacheTable(t.table),this.cache[i]}cacheTable(t){const e=t[It.Symbol.Schema]??"public",n=t[It.Symbol.OriginalName],i=`${e}.${n}`;if(!this.cachedTables[i]){for(const s of Object.values(t[It.Symbol.Columns])){const o=`${i}.${s.name}`;this.cache[o]=this.convert(s.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}W(XT,N_,"CasingCache");var B_,U_;class kp extends(U_=ji,B_=St,U_){}W(kp,B_,"PgViewBase");var k_;k_=St;class Ea{constructor(t){W(this,"casing");this.casing=new XT(t==null?void 0:t.casing)}async migrate(t,e,n){const i=typeof n=="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",s=typeof n=="string"?"drizzle":n.migrationsSchema??"drizzle",o=Y` CREATE TABLE IF NOT EXISTS ${Y.identifier(s)}.${Y.identifier(i)} ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint ) - `;await e.execute(Y`CREATE SCHEMA IF NOT EXISTS ${Y.identifier(s)}`),await e.execute(o);const l=(await e.all(Y`select id, hash, created_at from ${Y.identifier(s)}.${Y.identifier(i)} order by created_at desc limit 1`))[0];await e.transaction(async u=>{for await(const c of t)if(!l||Number(l.created_at){var a;return e[o]!==void 0||((a=n[o])==null?void 0:a.onUpdateFn)!==void 0}),s=i.length;return Y.join(i.flatMap((o,a)=>{const l=n[o],u=e[o]??Y.param(l.onUpdateFn(),l),c=Y`${Y.identifier(this.casing.getColumnCasing(l))} = ${u}`;return a{const a=[];if(lt(s,Pt.Aliased)&&s.isSelectionField)a.push(Y.identifier(s.fieldAlias));else if(lt(s,Pt.Aliased)||lt(s,Pt)){const l=lt(s,Pt.Aliased)?s.sql:s;e?a.push(new Pt(l.queryChunks.map(u=>lt(u,Lr)?Y.identifier(this.casing.getColumnCasing(u)):u))):a.push(l),lt(s,Pt.Aliased)&&a.push(Y` as ${Y.identifier(s.fieldAlias)}`)}else lt(s,rr)&&(e?a.push(Y.identifier(this.casing.getColumnCasing(s))):a.push(s));return oa==null?void 0:a.some(({alias:P})=>P===(nt[Tt.Symbol.IsAlias]?vs(nt):nt[Tt.Symbol.BaseName])))(x.field.table)){const nt=vs(x.field.table);throw new Error(`Your "${x.path.join("->")}" field references a column "${nt}"."${x.field.name}", but the table "${nt}" is not part of the query! Did you forget to join it?`)}const p=!a||a.length===0,y=this.buildWithCTE(t);let _;d&&(_=d===!0?Y` distinct`:Y` distinct on (${Y.join(d.on,Y`, `)})`);const S=this.buildSelection(g,{isSingleTable:p}),T=this.buildFromTable(o),v=this.buildJoins(a),E=i?Y` where ${i}`:void 0,w=s?Y` having ${s}`:void 0;let B;l&&l.length>0&&(B=Y` order by ${Y.join(l,Y`, `)}`);let N;u&&u.length>0&&(N=Y` group by ${Y.join(u,Y`, `)}`);const $=typeof c=="object"||typeof c=="number"&&c>=0?Y` limit ${c}`:void 0,it=h?Y` offset ${h}`:void 0,I=Y.empty();if(f){const x=Y` for ${Y.raw(f.strength)}`;f.config.of&&x.append(Y` of ${Y.join(Array.isArray(f.config.of)?f.config.of:[f.config.of],Y`, `)}`),f.config.noWait?x.append(Y` no wait`):f.config.skipLocked&&x.append(Y` skip locked`),I.append(x)}const Z=Y`${y}select${_} ${S} from ${T}${v}${E}${N}${w}${B}${$}${it}${I}`;return m.length>0?this.buildSetOperations(Z,m):Z}buildSetOperations(t,e){const[n,...i]=e;if(!n)throw new Error("Cannot pass undefined values to any set operator");return i.length===0?this.buildSetOperationQuery({leftSelect:t,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:t,setOperator:n}),i)}buildSetOperationQuery({leftSelect:t,setOperator:{type:e,isAll:n,rightSelect:i,limit:s,orderBy:o,offset:a}}){const l=Y`(${t.getSQL()}) `,u=Y`(${i.getSQL()})`;let c;if(o&&o.length>0){const m=[];for(const g of o)if(lt(g,Lr))m.push(Y.identifier(g.name));else if(lt(g,Pt)){for(let p=0;p=0?Y` limit ${s}`:void 0,f=Y.raw(`${e} ${n?"all ":""}`),d=a?Y` offset ${a}`:void 0;return Y`${l}${f}${u}${c}${h}${d}`}buildInsertQuery({table:t,values:e,onConflict:n,returning:i,withList:s,select:o,overridingSystemValue_:a}){const l=[],u=t[Tt.Symbol.Columns],c=Object.entries(u).filter(([y,_])=>!_.shouldDisableInsert()),h=c.map(([,y])=>Y.identifier(this.casing.getColumnCasing(y)));if(o){const y=e;lt(y,Pt)?l.push(y):l.push(y.getSQL())}else{const y=e;l.push(Y.raw("values "));for(const[_,S]of y.entries()){const T=[];for(const[v,E]of c){const w=S[v];if(w===void 0||lt(w,ci)&&w.value===void 0)if(E.defaultFn!==void 0){const B=E.defaultFn(),N=lt(B,Pt)?B:Y.param(B,E);T.push(N)}else if(!E.default&&E.onUpdateFn!==void 0){const B=E.onUpdateFn(),N=lt(B,Pt)?B:Y.param(B,E);T.push(N)}else T.push(Y`default`);else T.push(w)}l.push(T),_({dbKey:S.name,tsKey:_,field:ei(S,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const y=Object.fromEntries(Object.entries(s.columns).map(([w,B])=>[w,ei(B,a)]));if(o.where){const w=typeof o.where=="function"?o.where(y,wk()):o.where;m=w&&Xu(w,a)}const _=[];let S=[];if(o.columns){let w=!1;for(const[B,N]of Object.entries(o.columns))N!==void 0&&B in s.columns&&(!w&&N===!0&&(w=!0),S.push(B));S.length>0&&(S=w?S.filter(B=>{var N;return((N=o.columns)==null?void 0:N[B])===!0}):Object.keys(s.columns).filter(B=>!S.includes(B)))}else S=Object.keys(s.columns);for(const w of S){const B=s.columns[w];_.push({tsKey:w,value:B})}let T=[];o.with&&(T=Object.entries(o.with).filter(w=>!!w[1]).map(([w,B])=>({tsKey:w,queryConfig:B,relation:s.relations[w]})));let v;if(o.extras){v=typeof o.extras=="function"?o.extras(y,{sql:Y}):o.extras;for(const[w,B]of Object.entries(v))_.push({tsKey:w,value:MT(B,a)})}for(const{tsKey:w,value:B}of _)c.push({dbKey:lt(B,Pt.Aliased)?B.fieldAlias:s.columns[w].name,tsKey:w,field:lt(B,rr)?ei(B,a):B,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof o.orderBy=="function"?o.orderBy(y,xk()):o.orderBy??[];Array.isArray(E)||(E=[E]),d=E.map(w=>lt(w,rr)?ei(w,a):Xu(w,a)),h=o.limit,f=o.offset;for(const{tsKey:w,queryConfig:B,relation:N}of T){const $=Ek(e,n,N),it=Xa(N.referencedTable),I=n[it],Z=`${a}_${w}`,x=gf(...$.fields.map((C,R)=>OT(ei($.references[R],Z),ei(C,a)))),nt=this.buildRelationalQueryWithoutPK({fullSchema:t,schema:e,tableNamesMap:n,table:t[I],tableConfig:e[I],queryConfig:lt(N,Os)?B===!0?{limit:1}:{...B,limit:1}:B,tableAlias:Z,joinOn:x,nestedQueryRelation:N}),P=Y`${Y.identifier(Z)}.${Y.identifier("data")}`.as(w);g.push({on:Y`true`,table:new Nr(nt.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),c.push({dbKey:w,tsKey:w,field:P,relationTableTsKey:I,isJson:!0,selection:nt.selection})}}if(c.length===0)throw new Np({message:`No fields selected for table "${s.tsName}" ("${a}")`});let p;if(m=gf(u,m),l){let y=Y`json_build_array(${Y.join(c.map(({field:T,tsKey:v,isJson:E})=>E?Y`${Y.identifier(`${a}_${v}`)}.${Y.identifier("data")}`:lt(T,Pt.Aliased)?T.sql:T),Y`, `)})`;lt(l,Yu)&&(y=Y`coalesce(json_agg(${y}${d.length>0?Y` order by ${Y.join(d,Y`, `)}`:void 0}), '[]'::json)`);const _=[{dbKey:"data",tsKey:"data",field:y.as("data"),isJson:!0,relationTableTsKey:s.tsName,selection:c}];h!==void 0||f!==void 0||d.length>0?(p=this.buildSelectQuery({table:$h(i,a),fields:{},fieldsFlat:[{path:[],field:Y.raw("*")}],where:m,limit:h,offset:f,orderBy:d,setOperators:[]}),m=void 0,h=void 0,f=void 0,d=[]):p=$h(i,a),p=this.buildSelectQuery({table:lt(p,Xr)?p:new Nr(p,{},a),fields:{},fieldsFlat:_.map(({field:T})=>({path:[],field:lt(T,rr)?ei(T,a):T})),joins:g,where:m,limit:h,offset:f,orderBy:d,setOperators:[]})}else p=this.buildSelectQuery({table:$h(i,a),fields:{},fieldsFlat:c.map(({field:y})=>({path:[],field:lt(y,rr)?ei(y,a):y})),joins:g,where:m,limit:h,offset:f,orderBy:d,setOperators:[]});return{tableTsKey:s.tsName,sql:p,selection:c}}}W(Ea,k_,"PgDialect");var z_;z_=St;class YT{getSelectedFields(){return this._.selectedFields}}W(YT,z_,"TypedQueryBuilder");var V_;V_=St;class Or{constructor(t){W(this,"fields");W(this,"session");W(this,"dialect");W(this,"withList",[]);W(this,"distinct");W(this,"authToken");this.fields=t.fields,this.session=t.session,this.dialect=t.dialect,t.withList&&(this.withList=t.withList),this.distinct=t.distinct}setToken(t){return this.authToken=t,this}from(t){const e=!!this.fields,n=t;let i;return this.fields?i=this.fields:lt(n,Nr)?i=Object.fromEntries(Object.keys(n._.selectedFields).map(s=>[s,n[s]])):lt(n,kp)?i=n[Qe].selectedFields:lt(n,Pt)?i={}:i=_k(n),new zp({table:n,fields:i,isPartialSelect:e,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}W(Or,V_,"PgSelectBuilder");var j_,$_;class qT extends($_=YT,j_=St,$_){constructor({table:e,fields:n,isPartialSelect:i,session:s,dialect:o,withList:a,distinct:l}){super();W(this,"_");W(this,"config");W(this,"joinsNotNullableMap");W(this,"tableName");W(this,"isPartialSelect");W(this,"session");W(this,"dialect");W(this,"leftJoin",this.createJoin("left"));W(this,"rightJoin",this.createJoin("right"));W(this,"innerJoin",this.createJoin("inner"));W(this,"fullJoin",this.createJoin("full"));W(this,"union",this.createSetOperator("union",!1));W(this,"unionAll",this.createSetOperator("union",!0));W(this,"intersect",this.createSetOperator("intersect",!1));W(this,"intersectAll",this.createSetOperator("intersect",!0));W(this,"except",this.createSetOperator("except",!1));W(this,"exceptAll",this.createSetOperator("except",!0));this.config={withList:a,table:e,fields:{...n},distinct:l,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=o,this._={selectedFields:n},this.tableName=fs(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(n,i)=>{var a;const s=this.tableName,o=fs(n);if(typeof o=="string"&&((a=this.config.joins)!=null&&a.some(l=>l.alias===o)))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof o=="string"&&!lt(n,Pt))){const l=lt(n,Nr)?n._.selectedFields:lt(n,ji)?n[Qe].selectedFields:n[Tt.Symbol.Columns];this.config.fields[o]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:n,joinType:e,alias:o}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!0;break}case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}createSetOperator(e,n){return i=>{const s=typeof i=="function"?i(Pk()):i;if(!Bp(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:n,rightSelect:s}),this}}addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const n=e[0](new Proxy(this.config.fields,new or({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const n=e[0](new Proxy(this.config.fields,new or({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(n)?n:[n];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{const n=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,n={}){return this.config.lockingClause={strength:e,config:n},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(e){return new Proxy(new Nr(this.getSQL(),this.config.fields,e),new or({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new or({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}W(qT,j_,"PgSelectQueryBuilder");var G_,W_;class zp extends(W_=qT,G_=St,W_){constructor(){super(...arguments);W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)))}_prepare(e){const{session:n,config:i,dialect:s,joinsNotNullableMap:o,authToken:a}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Ur.startActiveSpan("drizzle.prepareQuery",()=>{const l=Cs(i.fields),u=n.prepareQuery(s.sqlToQuery(this.getSQL()),l,e,!0);return u.joinsNotNullableMap=o,u.setToken(a)})}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}}W(zp,G_,"PgSelect");vk(zp,[$i]);function zo(r,t){return(e,n,...i)=>{const s=[n,...i].map(o=>({type:r,isAll:t,rightSelect:o}));for(const o of s)if(!Bp(e.getSelectedFields(),o.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return e.addSetOperators(s)}}const Pk=()=>({union:Rk,unionAll:Fk,intersect:Dk,intersectAll:Lk,except:Nk,exceptAll:Bk}),Rk=zo("union",!1),Fk=zo("union",!0),Dk=zo("intersect",!1),Lk=zo("intersect",!0),Nk=zo("except",!1),Bk=zo("except",!0);var H_;H_=St;class Vp{constructor(t){W(this,"dialect");W(this,"dialectConfig");W(this,"$with",(t,e)=>{const n=this;return{as:s=>(typeof s=="function"&&(s=s(n)),new Proxy(new Lp(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new or({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});this.dialect=lt(t,Ea)?t:void 0,this.dialectConfig=lt(t,Ea)?void 0:t}with(...t){const e=this;function n(o){return new Or({fields:o??void 0,session:void 0,dialect:e.getDialect(),withList:t})}function i(o){return new Or({fields:o??void 0,session:void 0,dialect:e.getDialect(),distinct:!0})}function s(o,a){return new Or({fields:a??void 0,session:void 0,dialect:e.getDialect(),distinct:{on:o}})}return{select:n,selectDistinct:i,selectDistinctOn:s}}select(t){return new Or({fields:t??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(t){return new Or({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(t,e){return new Or({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:t}})}getDialect(){return this.dialect||(this.dialect=new Ea(this.dialectConfig)),this.dialect}}W(Vp,H_,"PgQueryBuilder");var X_;X_=St;class _f{constructor(t,e,n,i,s){W(this,"authToken");this.table=t,this.session=e,this.dialect=n,this.withList=i,this.overridingSystemValue_=s}setToken(t){return this.authToken=t,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(t){if(t=Array.isArray(t)?t:[t],t.length===0)throw new Error("values() must be called with at least one value");const e=t.map(n=>{const i={},s=this.table[Tt.Symbol.Columns];for(const o of Object.keys(n)){const a=n[o];i[o]=lt(a,Pt)?a:new ci(a,s[o])}return i});return new bf(this.table,e,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(t){const e=typeof t=="function"?t(new Vp):t;if(!lt(e,Pt)&&!Bp(this.table[mf],e._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new bf(this.table,e,this.session,this.dialect,this.withList,!0)}}W(_f,X_,"PgInsertBuilder");var Y_,q_;class bf extends(q_=$i,Y_=St,q_){constructor(e,n,i,s,o,a,l){super();W(this,"config");W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=i,this.dialect=s,this.config={table:e,values:n,withList:o,select:a,overridingSystemValue_:l}}returning(e=this.config.table[Tt.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Cs(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=Y`do nothing`;else{let n="";n=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));const i=e.where?Y` where ${e.where}`:void 0;this.config.onConflict=Y`(${Y.raw(n)})${i} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');const n=e.where?Y` where ${e.where}`:void 0,i=e.targetWhere?Y` where ${e.targetWhere}`:void 0,s=e.setWhere?Y` where ${e.setWhere}`:void 0,o=this.dialect.buildUpdateSet(this.config.table,DT(this.config.table,e.set));let a="";return a=Array.isArray(e.target)?e.target.map(l=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(l))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=Y`(${Y.raw(a)})${i} do update set ${o}${n}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0))}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new or({alias:vs(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}W(bf,Y_,"PgInsert");var Q_,Z_;class QT extends(Z_=$i,Q_=St,Z_){constructor(e,n,i){super();W(this,"config");W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=n,this.dialect=i,this.config={view:e}}concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}}W(QT,Q_,"PgRefreshMaterializedView");var K_;K_=St;class wf{constructor(t,e,n,i){W(this,"authToken");this.table=t,this.session=e,this.dialect=n,this.withList=i}setToken(t){return this.authToken=t,this}set(t){return new ZT(this.table,DT(this.table,t),this.session,this.dialect,this.withList).setToken(this.authToken)}}W(wf,K_,"PgUpdateBuilder");var J_,t0;class ZT extends(t0=$i,J_=St,t0){constructor(e,n,i,s,o){super();W(this,"config");W(this,"tableName");W(this,"joinsNotNullableMap");W(this,"leftJoin",this.createJoin("left"));W(this,"rightJoin",this.createJoin("right"));W(this,"innerJoin",this.createJoin("inner"));W(this,"fullJoin",this.createJoin("full"));W(this,"authToken");W(this,"execute",e=>this._prepare().execute(e,this.authToken));this.session=i,this.dialect=s,this.config={set:n,table:e,withList:o,joins:[]},this.tableName=fs(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}from(e){const n=e,i=fs(n);return typeof i=="string"&&(this.joinsNotNullableMap[i]=!0),this.config.from=n,this}getTableLikeFields(e){return lt(e,Xr)?e[Tt.Symbol.Columns]:lt(e,Nr)?e._.selectedFields:e[Qe].selectedFields}createJoin(e){return(n,i)=>{const s=fs(n);if(typeof s=="string"&&this.config.joins.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){const o=this.config.from&&!lt(this.config.from,Pt)?this.getTableLikeFields(this.config.from):void 0;i=i(new Proxy(this.config.table[Tt.Symbol.Columns],new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:i,table:n,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[Tt.Symbol.Columns]),this.config.from)){const n=fs(this.config.from);if(typeof n=="string"&&this.config.from&&!lt(this.config.from,Pt)){const i=this.getTableLikeFields(this.config.from);e[n]=i}for(const i of this.config.joins){const s=fs(i.table);if(typeof s=="string"&&!lt(i.table,Pt)){const o=this.getTableLikeFields(i.table);e[s]=o}}}return this.config.returningFields=e,this.config.returning=Cs(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){const n=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new or({alias:vs(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}W(ZT,J_,"PgUpdate");var e0,r0,n0;const Ma=class Ma extends(n0=Pt,r0=St,e0=Symbol.toStringTag,n0){constructor(e){super(Ma.buildEmbeddedCount(e.source,e.filters).queryChunks);W(this,"sql");W(this,"token");W(this,e0,"PgCountBuilder");W(this,"session");this.params=e,this.mapWith(Number),this.session=e.session,this.sql=Ma.buildCount(e.source,e.filters)}static buildEmbeddedCount(e,n){return Y`(select count(*) from ${e}${Y.raw(" where ").if(n)}${n})`}static buildCount(e,n){return Y`select count(*) as count from ${e}${Y.raw(" where ").if(n)}${n};`}setToken(e){return this.token=e,this}then(e,n){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,n)}catch(e){return this.then(void 0,e)}finally(e){return this.then(n=>(e==null||e(),n),n=>{throw e==null||e(),n})}};W(Ma,r0,"PgCountBuilder");let xf=Ma;var i0;i0=St;class KT{constructor(t,e,n,i,s,o,a){this.fullSchema=t,this.schema=e,this.tableNamesMap=n,this.table=i,this.tableConfig=s,this.dialect=o,this.session=a}findMany(t){return new Sf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t||{},"many")}findFirst(t){return new Sf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t?{...t,limit:1}:{limit:1},"first")}}W(KT,i0,"PgRelationalQueryBuilder");var s0,o0;class Sf extends(o0=$i,s0=St,o0){constructor(e,n,i,s,o,a,l,u,c){super();W(this,"authToken");this.fullSchema=e,this.schema=n,this.tableNamesMap=i,this.table=s,this.tableConfig=o,this.dialect=a,this.session=l,this.config=u,this.mode=c}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>{const{query:n,builtQuery:i}=this._toSQL();return this.session.prepareQuery(i,void 0,e,!0,(s,o)=>{const a=s.map(l=>yf(this.schema,this.tableConfig,l,n.selection,o));return this.mode==="first"?a[0]:a})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){const e=this._getQuery(),n=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}setToken(e){return this.authToken=e,this}execute(){return Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}}W(Sf,s0,"PgRelationalQuery");var a0,l0;class JT extends(l0=$i,a0=St,l0){constructor(t,e,n,i){super(),this.execute=t,this.sql=e,this.query=n,this.mapBatchResult=i}getSQL(){return this.sql}getQuery(){return this.query}mapResult(t,e){return e?this.mapBatchResult(t):t}_prepare(){return this}isResponseInArrayMode(){return!1}}W(JT,a0,"PgRaw");var u0;u0=St;class jp{constructor(t,e,n){W(this,"query");W(this,"$with",(t,e)=>{const n=this;return{as:s=>(typeof s=="function"&&(s=s(new Vp(n.dialect))),new Proxy(new Lp(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new or({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});W(this,"authToken");if(this.dialect=t,this.session=e,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:e}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:e},this.query={},this._.schema)for(const[i,s]of Object.entries(this._.schema))this.query[i]=new KT(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[i],s,t,e)}$count(t,e){return new xf({source:t,filters:e,session:this.session})}with(...t){const e=this;function n(u){return new Or({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t})}function i(u){return new Or({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:!0})}function s(u,c){return new Or({fields:c??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:{on:u}})}function o(u){return new wf(u,e.session,e.dialect,t)}function a(u){return new _f(u,e.session,e.dialect,t)}function l(u){return new vf(u,e.session,e.dialect,t)}return{select:n,selectDistinct:i,selectDistinctOn:s,update:o,insert:a,delete:l}}select(t){return new Or({fields:t??void 0,session:this.session,dialect:this.dialect})}selectDistinct(t){return new Or({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(t,e){return new Or({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:{on:t}})}update(t){return new wf(t,this.session,this.dialect)}insert(t){return new _f(t,this.session,this.dialect)}delete(t){return new vf(t,this.session,this.dialect)}refreshMaterializedView(t){return new QT(t,this.session,this.dialect)}execute(t){const e=typeof t=="string"?Y.raw(t):t.getSQL(),n=this.dialect.sqlToQuery(e),i=this.session.prepareQuery(n,void 0,void 0,!1);return new JT(()=>i.execute(void 0,this.authToken),e,n,s=>i.mapResult(s,!0))}transaction(t,e){return this.session.transaction(t,e)}}W(jp,u0,"PgDatabase");var c0;c0=St;class t1{constructor(t){W(this,"authToken");W(this,"joinsNotNullableMap");this.query=t}getQuery(){return this.query}mapResult(t,e){return t}setToken(t){return this.authToken=t,this}}W(t1,c0,"PgPreparedQuery");var h0;h0=St;class e1{constructor(t){this.dialect=t}execute(t,e){return Ur.startActiveSpan("drizzle.operation",()=>Ur.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(t),void 0,void 0,!1)).setToken(e).execute(void 0,e))}all(t){return this.prepareQuery(this.dialect.sqlToQuery(t),void 0,void 0,!1).all()}async count(t,e){const n=await this.execute(t,e);return Number(n[0].count)}}W(e1,h0,"PgSession");var d0,f0;class r1 extends(f0=jp,d0=St,f0){constructor(t,e,n,i=0){super(t,e,n),this.schema=n,this.nestedIndex=i}rollback(){throw new CT}getTransactionConfigSQL(t){const e=[];return t.isolationLevel&&e.push(`isolation level ${t.isolationLevel}`),t.accessMode&&e.push(t.accessMode),typeof t.deferrable=="boolean"&&e.push(t.deferrable?"deferrable":"not deferrable"),Y.raw(e.join(" "))}setTransaction(t){return this.session.execute(Y`set transaction ${this.getTransactionConfigSQL(t)}`)}}W(r1,d0,"PgTransaction");function gv(r){return typeof r=="string"&&/^true$/i.test(r)}function Uk(r){const t={scheme:"duckdb-wasm:"},e=new URL(r);if(!e.protocol.startsWith("duckdb-wasm:"))throw new Error(`Expected scheme to be "duckdb-wasm:" but got "${e.protocol}"`);e.searchParams.get("bundles")==="import-url"&&(t.bundles="import-url");const n=e.searchParams.get("logger");n&&gv(n)&&(t.logger=!0);const i=e.searchParams.get("storage");switch(i){case Ha.ORIGIN_PRIVATE_FS:{e.host.length>0&&console.warn(`Host "${e.host}" will be ignored while using Origin Private FS`);const s=e.searchParams.get("write");t.storage={type:Ha.ORIGIN_PRIVATE_FS,path:e.pathname.startsWith("/")?e.pathname.slice(1):e.pathname,...s&&gv(s)&&{accessMode:Nx.READ_WRITE}};break}case null:break;default:console.warn(`Unknown storage type "${i}"`);break}return t}var p0,m0;class n1 extends(m0=t1,p0=St,m0){constructor(t,e,n,i,s,o){super({sql:e,params:n}),this.client=t,this.queryString=e,this.params=n,this.logger=i,this.fields=s,this.customResultMapper=o}async execute(t={}){const e=fv(this.params,t);this.logger.logQuery(this.queryString,e);const{fields:n,queryString:i,client:s,customResultMapper:o}=this,a=await s;return a.query(i,e)}async all(t={}){const e=fv(this.params,t);return this.logger.logQuery(this.queryString,e),(await this.client).query(this.queryString,e)}}W(n1,p0,"DuckDBWasmPreparedQuery");var g0,y0;const Ju=class Ju extends(y0=e1,g0=St,y0){constructor(e,n,i,s={}){super(n);W(this,"logger");this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new FT}prepareQuery(e,n,i,s,o){return new n1(this.client,e.sql,e.params,this.logger,n,o)}async query(e,n){return this.logger.logQuery(e,n),(await this.client).query(e,n)}async queryObjects(e,n){return this.logger.logQuery(e,n),(await this.client).query(e,n)}transaction(e,n){return $U(this.client,async i=>{const s=new Ju(i,this.dialect,this.schema,this.options),o=new Tf(this.dialect,s,this.schema);return n&&await o.setTransaction(n),e(o)})}};W(Ju,g0,"DuckDBWasmSession");let qu=Ju;var v0,_0;const tc=class tc extends(_0=r1,v0=St,_0){constructor(e,n,i,s=0){super(e,n,i,s);W(this,"dialect");W(this,"session");this.dialect=e,this.session=n}async transaction(e){return GU(this.session.client,"",async n=>{const i=new qu(n,this.dialect,this.schema,this.session.options),s=new tc(this.dialect,i,this.schema);return e(s)})}};W(tc,v0,"DuckDBWasmTransaction");let Tf=tc;var b0,w0;class i1 extends(w0=jp,b0=St,w0){}W(i1,b0,"DuckDBWasmDatabase");function Aa(r,t={}){const e=new Ea({casing:t.casing});let n;t.logger===!0?n=new RT:t.logger!==!1&&(n=t.logger);let i;if(t.schema){const a=Sk(t.schema,Ak);i={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}const s=new qu(r,e,i,{logger:n}),o=new i1(e,s,i);return o.$client=r,o}async function kk(r=!1){const t=await xT();switch(t){case"browser":return r?(await Ei(async()=>{const{getImportUrlBundles:e}=await import("./import-url-browser-CPN8ipMD.js");return{getImportUrlBundles:e}},__vite__mapDeps([3,4]))).getImportUrlBundles():(await Ei(async()=>{const{getBundles:e}=await import("./default-browser-BrgSDbLD.js");return{getBundles:e}},[])).getBundles();case"node":return r?await(await Ei(async()=>{const{getImportUrlBundles:e}=await import("./import-url-node-BfNoxhRr.js");return{getImportUrlBundles:e}},__vite__mapDeps([5,4]))).getImportUrlBundles():await(await Ei(async()=>{const{getBundles:e}=await import("./default-node-CM_FKz7Y.js");return{getBundles:e}},__vite__mapDeps([0,1,2]))).getBundles();default:throw new Error(`Unsupported environment: "${t}"`)}}function yv(r,t){const e=Uk(r);return Aa(TT({bundles:kk(e.bundles==="import-url"),logger:e.logger?new Bx:void 0,storage:e.storage}),t)}function vv(...r){if(typeof r[0]=="string")return yv(r[0],r[1]);if(bk(r[0])){const{connection:t,client:e,...n}=r[0];if(e)return Aa(e,n);if(typeof t=="string")return yv(t,n);if(typeof t>"u")throw new Error("connection option is required");return Aa(TT({bundles:t.bundles,logger:t.logger,storage:t.storage}),n)}return Aa(r[0],r[1])}(r=>{function t(e){return Aa({options:{parsers:{},serializers:{}}},e)}r.mock=t})(vv||(vv={}));var Gh={exports:{}};/*! + `;await e.execute(Y`CREATE SCHEMA IF NOT EXISTS ${Y.identifier(s)}`),await e.execute(o);const l=(await e.all(Y`select id, hash, created_at from ${Y.identifier(s)}.${Y.identifier(i)} order by created_at desc limit 1`))[0];await e.transaction(async u=>{for await(const c of t)if(!l||Number(l.created_at){var a;return e[o]!==void 0||((a=n[o])==null?void 0:a.onUpdateFn)!==void 0}),s=i.length;return Y.join(i.flatMap((o,a)=>{const l=n[o],u=e[o]??Y.param(l.onUpdateFn(),l),c=Y`${Y.identifier(this.casing.getColumnCasing(l))} = ${u}`;return a{const a=[];if(lt(s,Pt.Aliased)&&s.isSelectionField)a.push(Y.identifier(s.fieldAlias));else if(lt(s,Pt.Aliased)||lt(s,Pt)){const l=lt(s,Pt.Aliased)?s.sql:s;e?a.push(new Pt(l.queryChunks.map(u=>lt(u,Lr)?Y.identifier(this.casing.getColumnCasing(u)):u))):a.push(l),lt(s,Pt.Aliased)&&a.push(Y` as ${Y.identifier(s.fieldAlias)}`)}else lt(s,rr)&&(e?a.push(Y.identifier(this.casing.getColumnCasing(s))):a.push(s));return oa==null?void 0:a.some(({alias:P})=>P===(nt[It.Symbol.IsAlias]?vs(nt):nt[It.Symbol.BaseName])))(x.field.table)){const nt=vs(x.field.table);throw new Error(`Your "${x.path.join("->")}" field references a column "${nt}"."${x.field.name}", but the table "${nt}" is not part of the query! Did you forget to join it?`)}const p=!a||a.length===0,y=this.buildWithCTE(t);let _;d&&(_=d===!0?Y` distinct`:Y` distinct on (${Y.join(d.on,Y`, `)})`);const S=this.buildSelection(g,{isSingleTable:p}),T=this.buildFromTable(o),v=this.buildJoins(a),E=i?Y` where ${i}`:void 0,w=s?Y` having ${s}`:void 0;let B;l&&l.length>0&&(B=Y` order by ${Y.join(l,Y`, `)}`);let N;u&&u.length>0&&(N=Y` group by ${Y.join(u,Y`, `)}`);const $=typeof c=="object"||typeof c=="number"&&c>=0?Y` limit ${c}`:void 0,it=h?Y` offset ${h}`:void 0,I=Y.empty();if(f){const x=Y` for ${Y.raw(f.strength)}`;f.config.of&&x.append(Y` of ${Y.join(Array.isArray(f.config.of)?f.config.of:[f.config.of],Y`, `)}`),f.config.noWait?x.append(Y` no wait`):f.config.skipLocked&&x.append(Y` skip locked`),I.append(x)}const Z=Y`${y}select${_} ${S} from ${T}${v}${E}${N}${w}${B}${$}${it}${I}`;return m.length>0?this.buildSetOperations(Z,m):Z}buildSetOperations(t,e){const[n,...i]=e;if(!n)throw new Error("Cannot pass undefined values to any set operator");return i.length===0?this.buildSetOperationQuery({leftSelect:t,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:t,setOperator:n}),i)}buildSetOperationQuery({leftSelect:t,setOperator:{type:e,isAll:n,rightSelect:i,limit:s,orderBy:o,offset:a}}){const l=Y`(${t.getSQL()}) `,u=Y`(${i.getSQL()})`;let c;if(o&&o.length>0){const m=[];for(const g of o)if(lt(g,Lr))m.push(Y.identifier(g.name));else if(lt(g,Pt)){for(let p=0;p=0?Y` limit ${s}`:void 0,f=Y.raw(`${e} ${n?"all ":""}`),d=a?Y` offset ${a}`:void 0;return Y`${l}${f}${u}${c}${h}${d}`}buildInsertQuery({table:t,values:e,onConflict:n,returning:i,withList:s,select:o,overridingSystemValue_:a}){const l=[],u=t[It.Symbol.Columns],c=Object.entries(u).filter(([y,_])=>!_.shouldDisableInsert()),h=c.map(([,y])=>Y.identifier(this.casing.getColumnCasing(y)));if(o){const y=e;lt(y,Pt)?l.push(y):l.push(y.getSQL())}else{const y=e;l.push(Y.raw("values "));for(const[_,S]of y.entries()){const T=[];for(const[v,E]of c){const w=S[v];if(w===void 0||lt(w,ci)&&w.value===void 0)if(E.defaultFn!==void 0){const B=E.defaultFn(),N=lt(B,Pt)?B:Y.param(B,E);T.push(N)}else if(!E.default&&E.onUpdateFn!==void 0){const B=E.onUpdateFn(),N=lt(B,Pt)?B:Y.param(B,E);T.push(N)}else T.push(Y`default`);else T.push(w)}l.push(T),_({dbKey:S.name,tsKey:_,field:ei(S,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const y=Object.fromEntries(Object.entries(s.columns).map(([w,B])=>[w,ei(B,a)]));if(o.where){const w=typeof o.where=="function"?o.where(y,wk()):o.where;m=w&&Xu(w,a)}const _=[];let S=[];if(o.columns){let w=!1;for(const[B,N]of Object.entries(o.columns))N!==void 0&&B in s.columns&&(!w&&N===!0&&(w=!0),S.push(B));S.length>0&&(S=w?S.filter(B=>{var N;return((N=o.columns)==null?void 0:N[B])===!0}):Object.keys(s.columns).filter(B=>!S.includes(B)))}else S=Object.keys(s.columns);for(const w of S){const B=s.columns[w];_.push({tsKey:w,value:B})}let T=[];o.with&&(T=Object.entries(o.with).filter(w=>!!w[1]).map(([w,B])=>({tsKey:w,queryConfig:B,relation:s.relations[w]})));let v;if(o.extras){v=typeof o.extras=="function"?o.extras(y,{sql:Y}):o.extras;for(const[w,B]of Object.entries(v))_.push({tsKey:w,value:MT(B,a)})}for(const{tsKey:w,value:B}of _)c.push({dbKey:lt(B,Pt.Aliased)?B.fieldAlias:s.columns[w].name,tsKey:w,field:lt(B,rr)?ei(B,a):B,relationTableTsKey:void 0,isJson:!1,selection:[]});let E=typeof o.orderBy=="function"?o.orderBy(y,xk()):o.orderBy??[];Array.isArray(E)||(E=[E]),d=E.map(w=>lt(w,rr)?ei(w,a):Xu(w,a)),h=o.limit,f=o.offset;for(const{tsKey:w,queryConfig:B,relation:N}of T){const $=Ek(e,n,N),it=Xa(N.referencedTable),I=n[it],Z=`${a}_${w}`,x=gf(...$.fields.map((C,R)=>OT(ei($.references[R],Z),ei(C,a)))),nt=this.buildRelationalQueryWithoutPK({fullSchema:t,schema:e,tableNamesMap:n,table:t[I],tableConfig:e[I],queryConfig:lt(N,Os)?B===!0?{limit:1}:{...B,limit:1}:B,tableAlias:Z,joinOn:x,nestedQueryRelation:N}),P=Y`${Y.identifier(Z)}.${Y.identifier("data")}`.as(w);g.push({on:Y`true`,table:new Nr(nt.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),c.push({dbKey:w,tsKey:w,field:P,relationTableTsKey:I,isJson:!0,selection:nt.selection})}}if(c.length===0)throw new Np({message:`No fields selected for table "${s.tsName}" ("${a}")`});let p;if(m=gf(u,m),l){let y=Y`json_build_array(${Y.join(c.map(({field:T,tsKey:v,isJson:E})=>E?Y`${Y.identifier(`${a}_${v}`)}.${Y.identifier("data")}`:lt(T,Pt.Aliased)?T.sql:T),Y`, `)})`;lt(l,Yu)&&(y=Y`coalesce(json_agg(${y}${d.length>0?Y` order by ${Y.join(d,Y`, `)}`:void 0}), '[]'::json)`);const _=[{dbKey:"data",tsKey:"data",field:y.as("data"),isJson:!0,relationTableTsKey:s.tsName,selection:c}];h!==void 0||f!==void 0||d.length>0?(p=this.buildSelectQuery({table:$h(i,a),fields:{},fieldsFlat:[{path:[],field:Y.raw("*")}],where:m,limit:h,offset:f,orderBy:d,setOperators:[]}),m=void 0,h=void 0,f=void 0,d=[]):p=$h(i,a),p=this.buildSelectQuery({table:lt(p,Xr)?p:new Nr(p,{},a),fields:{},fieldsFlat:_.map(({field:T})=>({path:[],field:lt(T,rr)?ei(T,a):T})),joins:g,where:m,limit:h,offset:f,orderBy:d,setOperators:[]})}else p=this.buildSelectQuery({table:$h(i,a),fields:{},fieldsFlat:c.map(({field:y})=>({path:[],field:lt(y,rr)?ei(y,a):y})),joins:g,where:m,limit:h,offset:f,orderBy:d,setOperators:[]});return{tableTsKey:s.tsName,sql:p,selection:c}}}W(Ea,k_,"PgDialect");var z_;z_=St;class YT{getSelectedFields(){return this._.selectedFields}}W(YT,z_,"TypedQueryBuilder");var V_;V_=St;class Or{constructor(t){W(this,"fields");W(this,"session");W(this,"dialect");W(this,"withList",[]);W(this,"distinct");W(this,"authToken");this.fields=t.fields,this.session=t.session,this.dialect=t.dialect,t.withList&&(this.withList=t.withList),this.distinct=t.distinct}setToken(t){return this.authToken=t,this}from(t){const e=!!this.fields,n=t;let i;return this.fields?i=this.fields:lt(n,Nr)?i=Object.fromEntries(Object.keys(n._.selectedFields).map(s=>[s,n[s]])):lt(n,kp)?i=n[Qe].selectedFields:lt(n,Pt)?i={}:i=_k(n),new zp({table:n,fields:i,isPartialSelect:e,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}W(Or,V_,"PgSelectBuilder");var j_,$_;class qT extends($_=YT,j_=St,$_){constructor({table:e,fields:n,isPartialSelect:i,session:s,dialect:o,withList:a,distinct:l}){super();W(this,"_");W(this,"config");W(this,"joinsNotNullableMap");W(this,"tableName");W(this,"isPartialSelect");W(this,"session");W(this,"dialect");W(this,"leftJoin",this.createJoin("left"));W(this,"rightJoin",this.createJoin("right"));W(this,"innerJoin",this.createJoin("inner"));W(this,"fullJoin",this.createJoin("full"));W(this,"union",this.createSetOperator("union",!1));W(this,"unionAll",this.createSetOperator("union",!0));W(this,"intersect",this.createSetOperator("intersect",!1));W(this,"intersectAll",this.createSetOperator("intersect",!0));W(this,"except",this.createSetOperator("except",!1));W(this,"exceptAll",this.createSetOperator("except",!0));this.config={withList:a,table:e,fields:{...n},distinct:l,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=o,this._={selectedFields:n},this.tableName=fs(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(n,i)=>{var a;const s=this.tableName,o=fs(n);if(typeof o=="string"&&((a=this.config.joins)!=null&&a.some(l=>l.alias===o)))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof o=="string"&&!lt(n,Pt))){const l=lt(n,Nr)?n._.selectedFields:lt(n,ji)?n[Qe].selectedFields:n[It.Symbol.Columns];this.config.fields[o]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:n,joinType:e,alias:o}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!0;break}case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}createSetOperator(e,n){return i=>{const s=typeof i=="function"?i(Pk()):i;if(!Bp(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:n,rightSelect:s}),this}}addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const n=e[0](new Proxy(this.config.fields,new or({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const n=e[0](new Proxy(this.config.fields,new or({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(n)?n:[n];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{const n=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,n={}){return this.config.lockingClause={strength:e,config:n},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(e){return new Proxy(new Nr(this.getSQL(),this.config.fields,e),new or({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new or({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}W(qT,j_,"PgSelectQueryBuilder");var G_,W_;class zp extends(W_=qT,G_=St,W_){constructor(){super(...arguments);W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)))}_prepare(e){const{session:n,config:i,dialect:s,joinsNotNullableMap:o,authToken:a}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Ur.startActiveSpan("drizzle.prepareQuery",()=>{const l=Cs(i.fields),u=n.prepareQuery(s.sqlToQuery(this.getSQL()),l,e,!0);return u.joinsNotNullableMap=o,u.setToken(a)})}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}}W(zp,G_,"PgSelect");vk(zp,[$i]);function zo(r,t){return(e,n,...i)=>{const s=[n,...i].map(o=>({type:r,isAll:t,rightSelect:o}));for(const o of s)if(!Bp(e.getSelectedFields(),o.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return e.addSetOperators(s)}}const Pk=()=>({union:Rk,unionAll:Fk,intersect:Dk,intersectAll:Lk,except:Nk,exceptAll:Bk}),Rk=zo("union",!1),Fk=zo("union",!0),Dk=zo("intersect",!1),Lk=zo("intersect",!0),Nk=zo("except",!1),Bk=zo("except",!0);var H_;H_=St;class Vp{constructor(t){W(this,"dialect");W(this,"dialectConfig");W(this,"$with",(t,e)=>{const n=this;return{as:s=>(typeof s=="function"&&(s=s(n)),new Proxy(new Lp(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new or({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});this.dialect=lt(t,Ea)?t:void 0,this.dialectConfig=lt(t,Ea)?void 0:t}with(...t){const e=this;function n(o){return new Or({fields:o??void 0,session:void 0,dialect:e.getDialect(),withList:t})}function i(o){return new Or({fields:o??void 0,session:void 0,dialect:e.getDialect(),distinct:!0})}function s(o,a){return new Or({fields:a??void 0,session:void 0,dialect:e.getDialect(),distinct:{on:o}})}return{select:n,selectDistinct:i,selectDistinctOn:s}}select(t){return new Or({fields:t??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(t){return new Or({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(t,e){return new Or({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:t}})}getDialect(){return this.dialect||(this.dialect=new Ea(this.dialectConfig)),this.dialect}}W(Vp,H_,"PgQueryBuilder");var X_;X_=St;class _f{constructor(t,e,n,i,s){W(this,"authToken");this.table=t,this.session=e,this.dialect=n,this.withList=i,this.overridingSystemValue_=s}setToken(t){return this.authToken=t,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(t){if(t=Array.isArray(t)?t:[t],t.length===0)throw new Error("values() must be called with at least one value");const e=t.map(n=>{const i={},s=this.table[It.Symbol.Columns];for(const o of Object.keys(n)){const a=n[o];i[o]=lt(a,Pt)?a:new ci(a,s[o])}return i});return new bf(this.table,e,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(t){const e=typeof t=="function"?t(new Vp):t;if(!lt(e,Pt)&&!Bp(this.table[mf],e._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new bf(this.table,e,this.session,this.dialect,this.withList,!0)}}W(_f,X_,"PgInsertBuilder");var Y_,q_;class bf extends(q_=$i,Y_=St,q_){constructor(e,n,i,s,o,a,l){super();W(this,"config");W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=i,this.dialect=s,this.config={table:e,values:n,withList:o,select:a,overridingSystemValue_:l}}returning(e=this.config.table[It.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=Cs(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=Y`do nothing`;else{let n="";n=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));const i=e.where?Y` where ${e.where}`:void 0;this.config.onConflict=Y`(${Y.raw(n)})${i} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');const n=e.where?Y` where ${e.where}`:void 0,i=e.targetWhere?Y` where ${e.targetWhere}`:void 0,s=e.setWhere?Y` where ${e.setWhere}`:void 0,o=this.dialect.buildUpdateSet(this.config.table,DT(this.config.table,e.set));let a="";return a=Array.isArray(e.target)?e.target.map(l=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(l))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=Y`(${Y.raw(a)})${i} do update set ${o}${n}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0))}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new or({alias:vs(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}W(bf,Y_,"PgInsert");var Q_,Z_;class QT extends(Z_=$i,Q_=St,Z_){constructor(e,n,i){super();W(this,"config");W(this,"authToken");W(this,"execute",e=>Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=n,this.dialect=i,this.config={view:e}}concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}}W(QT,Q_,"PgRefreshMaterializedView");var K_;K_=St;class wf{constructor(t,e,n,i){W(this,"authToken");this.table=t,this.session=e,this.dialect=n,this.withList=i}setToken(t){return this.authToken=t,this}set(t){return new ZT(this.table,DT(this.table,t),this.session,this.dialect,this.withList).setToken(this.authToken)}}W(wf,K_,"PgUpdateBuilder");var J_,t0;class ZT extends(t0=$i,J_=St,t0){constructor(e,n,i,s,o){super();W(this,"config");W(this,"tableName");W(this,"joinsNotNullableMap");W(this,"leftJoin",this.createJoin("left"));W(this,"rightJoin",this.createJoin("right"));W(this,"innerJoin",this.createJoin("inner"));W(this,"fullJoin",this.createJoin("full"));W(this,"authToken");W(this,"execute",e=>this._prepare().execute(e,this.authToken));this.session=i,this.dialect=s,this.config={set:n,table:e,withList:o,joins:[]},this.tableName=fs(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}from(e){const n=e,i=fs(n);return typeof i=="string"&&(this.joinsNotNullableMap[i]=!0),this.config.from=n,this}getTableLikeFields(e){return lt(e,Xr)?e[It.Symbol.Columns]:lt(e,Nr)?e._.selectedFields:e[Qe].selectedFields}createJoin(e){return(n,i)=>{const s=fs(n);if(typeof s=="string"&&this.config.joins.some(o=>o.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){const o=this.config.from&&!lt(this.config.from,Pt)?this.getTableLikeFields(this.config.from):void 0;i=i(new Proxy(this.config.table[It.Symbol.Columns],new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new or({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:i,table:n,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[It.Symbol.Columns]),this.config.from)){const n=fs(this.config.from);if(typeof n=="string"&&this.config.from&&!lt(this.config.from,Pt)){const i=this.getTableLikeFields(this.config.from);e[n]=i}for(const i of this.config.joins){const s=fs(i.table);if(typeof s=="string"&&!lt(i.table,Pt)){const o=this.getTableLikeFields(i.table);e[s]=o}}}return this.config.returningFields=e,this.config.returning=Cs(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:e,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(e){const n=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0);return n.joinsNotNullableMap=this.joinsNotNullableMap,n}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new or({alias:vs(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}W(ZT,J_,"PgUpdate");var e0,r0,n0;const Ma=class Ma extends(n0=Pt,r0=St,e0=Symbol.toStringTag,n0){constructor(e){super(Ma.buildEmbeddedCount(e.source,e.filters).queryChunks);W(this,"sql");W(this,"token");W(this,e0,"PgCountBuilder");W(this,"session");this.params=e,this.mapWith(Number),this.session=e.session,this.sql=Ma.buildCount(e.source,e.filters)}static buildEmbeddedCount(e,n){return Y`(select count(*) from ${e}${Y.raw(" where ").if(n)}${n})`}static buildCount(e,n){return Y`select count(*) as count from ${e}${Y.raw(" where ").if(n)}${n};`}setToken(e){return this.token=e,this}then(e,n){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,n)}catch(e){return this.then(void 0,e)}finally(e){return this.then(n=>(e==null||e(),n),n=>{throw e==null||e(),n})}};W(Ma,r0,"PgCountBuilder");let xf=Ma;var i0;i0=St;class KT{constructor(t,e,n,i,s,o,a){this.fullSchema=t,this.schema=e,this.tableNamesMap=n,this.table=i,this.tableConfig=s,this.dialect=o,this.session=a}findMany(t){return new Sf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t||{},"many")}findFirst(t){return new Sf(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t?{...t,limit:1}:{limit:1},"first")}}W(KT,i0,"PgRelationalQueryBuilder");var s0,o0;class Sf extends(o0=$i,s0=St,o0){constructor(e,n,i,s,o,a,l,u,c){super();W(this,"authToken");this.fullSchema=e,this.schema=n,this.tableNamesMap=i,this.table=s,this.tableConfig=o,this.dialect=a,this.session=l,this.config=u,this.mode=c}_prepare(e){return Ur.startActiveSpan("drizzle.prepareQuery",()=>{const{query:n,builtQuery:i}=this._toSQL();return this.session.prepareQuery(i,void 0,e,!0,(s,o)=>{const a=s.map(l=>yf(this.schema,this.tableConfig,l,n.selection,o));return this.mode==="first"?a[0]:a})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){const e=this._getQuery(),n=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}setToken(e){return this.authToken=e,this}execute(){return Ur.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}}W(Sf,s0,"PgRelationalQuery");var a0,l0;class JT extends(l0=$i,a0=St,l0){constructor(t,e,n,i){super(),this.execute=t,this.sql=e,this.query=n,this.mapBatchResult=i}getSQL(){return this.sql}getQuery(){return this.query}mapResult(t,e){return e?this.mapBatchResult(t):t}_prepare(){return this}isResponseInArrayMode(){return!1}}W(JT,a0,"PgRaw");var u0;u0=St;class jp{constructor(t,e,n){W(this,"query");W(this,"$with",(t,e)=>{const n=this;return{as:s=>(typeof s=="function"&&(s=s(new Vp(n.dialect))),new Proxy(new Lp(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new or({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});W(this,"authToken");if(this.dialect=t,this.session=e,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:e}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:e},this.query={},this._.schema)for(const[i,s]of Object.entries(this._.schema))this.query[i]=new KT(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[i],s,t,e)}$count(t,e){return new xf({source:t,filters:e,session:this.session})}with(...t){const e=this;function n(u){return new Or({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t})}function i(u){return new Or({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:!0})}function s(u,c){return new Or({fields:c??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:{on:u}})}function o(u){return new wf(u,e.session,e.dialect,t)}function a(u){return new _f(u,e.session,e.dialect,t)}function l(u){return new vf(u,e.session,e.dialect,t)}return{select:n,selectDistinct:i,selectDistinctOn:s,update:o,insert:a,delete:l}}select(t){return new Or({fields:t??void 0,session:this.session,dialect:this.dialect})}selectDistinct(t){return new Or({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(t,e){return new Or({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:{on:t}})}update(t){return new wf(t,this.session,this.dialect)}insert(t){return new _f(t,this.session,this.dialect)}delete(t){return new vf(t,this.session,this.dialect)}refreshMaterializedView(t){return new QT(t,this.session,this.dialect)}execute(t){const e=typeof t=="string"?Y.raw(t):t.getSQL(),n=this.dialect.sqlToQuery(e),i=this.session.prepareQuery(n,void 0,void 0,!1);return new JT(()=>i.execute(void 0,this.authToken),e,n,s=>i.mapResult(s,!0))}transaction(t,e){return this.session.transaction(t,e)}}W(jp,u0,"PgDatabase");var c0;c0=St;class t1{constructor(t){W(this,"authToken");W(this,"joinsNotNullableMap");this.query=t}getQuery(){return this.query}mapResult(t,e){return t}setToken(t){return this.authToken=t,this}}W(t1,c0,"PgPreparedQuery");var h0;h0=St;class e1{constructor(t){this.dialect=t}execute(t,e){return Ur.startActiveSpan("drizzle.operation",()=>Ur.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(t),void 0,void 0,!1)).setToken(e).execute(void 0,e))}all(t){return this.prepareQuery(this.dialect.sqlToQuery(t),void 0,void 0,!1).all()}async count(t,e){const n=await this.execute(t,e);return Number(n[0].count)}}W(e1,h0,"PgSession");var d0,f0;class r1 extends(f0=jp,d0=St,f0){constructor(t,e,n,i=0){super(t,e,n),this.schema=n,this.nestedIndex=i}rollback(){throw new CT}getTransactionConfigSQL(t){const e=[];return t.isolationLevel&&e.push(`isolation level ${t.isolationLevel}`),t.accessMode&&e.push(t.accessMode),typeof t.deferrable=="boolean"&&e.push(t.deferrable?"deferrable":"not deferrable"),Y.raw(e.join(" "))}setTransaction(t){return this.session.execute(Y`set transaction ${this.getTransactionConfigSQL(t)}`)}}W(r1,d0,"PgTransaction");function gv(r){return typeof r=="string"&&/^true$/i.test(r)}function Uk(r){const t={scheme:"duckdb-wasm:"},e=new URL(r);if(!e.protocol.startsWith("duckdb-wasm:"))throw new Error(`Expected scheme to be "duckdb-wasm:" but got "${e.protocol}"`);e.searchParams.get("bundles")==="import-url"&&(t.bundles="import-url");const n=e.searchParams.get("logger");n&&gv(n)&&(t.logger=!0);const i=e.searchParams.get("storage");switch(i){case Ha.ORIGIN_PRIVATE_FS:{e.host.length>0&&console.warn(`Host "${e.host}" will be ignored while using Origin Private FS`);const s=e.searchParams.get("write");t.storage={type:Ha.ORIGIN_PRIVATE_FS,path:e.pathname.startsWith("/")?e.pathname.slice(1):e.pathname,...s&&gv(s)&&{accessMode:Nx.READ_WRITE}};break}case null:break;default:console.warn(`Unknown storage type "${i}"`);break}return t}var p0,m0;class n1 extends(m0=t1,p0=St,m0){constructor(t,e,n,i,s,o){super({sql:e,params:n}),this.client=t,this.queryString=e,this.params=n,this.logger=i,this.fields=s,this.customResultMapper=o}async execute(t={}){const e=fv(this.params,t);this.logger.logQuery(this.queryString,e);const{fields:n,queryString:i,client:s,customResultMapper:o}=this,a=await s;return a.query(i,e)}async all(t={}){const e=fv(this.params,t);return this.logger.logQuery(this.queryString,e),(await this.client).query(this.queryString,e)}}W(n1,p0,"DuckDBWasmPreparedQuery");var g0,y0;const Ju=class Ju extends(y0=e1,g0=St,y0){constructor(e,n,i,s={}){super(n);W(this,"logger");this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new FT}prepareQuery(e,n,i,s,o){return new n1(this.client,e.sql,e.params,this.logger,n,o)}async query(e,n){return this.logger.logQuery(e,n),(await this.client).query(e,n)}async queryObjects(e,n){return this.logger.logQuery(e,n),(await this.client).query(e,n)}transaction(e,n){return $U(this.client,async i=>{const s=new Ju(i,this.dialect,this.schema,this.options),o=new Tf(this.dialect,s,this.schema);return n&&await o.setTransaction(n),e(o)})}};W(Ju,g0,"DuckDBWasmSession");let qu=Ju;var v0,_0;const tc=class tc extends(_0=r1,v0=St,_0){constructor(e,n,i,s=0){super(e,n,i,s);W(this,"dialect");W(this,"session");this.dialect=e,this.session=n}async transaction(e){return GU(this.session.client,"",async n=>{const i=new qu(n,this.dialect,this.schema,this.session.options),s=new tc(this.dialect,i,this.schema);return e(s)})}};W(tc,v0,"DuckDBWasmTransaction");let Tf=tc;var b0,w0;class i1 extends(w0=jp,b0=St,w0){}W(i1,b0,"DuckDBWasmDatabase");function Aa(r,t={}){const e=new Ea({casing:t.casing});let n;t.logger===!0?n=new RT:t.logger!==!1&&(n=t.logger);let i;if(t.schema){const a=Sk(t.schema,Ak);i={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}const s=new qu(r,e,i,{logger:n}),o=new i1(e,s,i);return o.$client=r,o}async function kk(r=!1){const t=await xT();switch(t){case"browser":return r?(await Ei(async()=>{const{getImportUrlBundles:e}=await import("./import-url-browser-CPN8ipMD.js");return{getImportUrlBundles:e}},__vite__mapDeps([3,4]))).getImportUrlBundles():(await Ei(async()=>{const{getBundles:e}=await import("./default-browser-BrgSDbLD.js");return{getBundles:e}},[])).getBundles();case"node":return r?await(await Ei(async()=>{const{getImportUrlBundles:e}=await import("./import-url-node-BfNoxhRr.js");return{getImportUrlBundles:e}},__vite__mapDeps([5,4]))).getImportUrlBundles():await(await Ei(async()=>{const{getBundles:e}=await import("./default-node-BIhtlSJe.js");return{getBundles:e}},__vite__mapDeps([0,1,2]))).getBundles();default:throw new Error(`Unsupported environment: "${t}"`)}}function yv(r,t){const e=Uk(r);return Aa(TT({bundles:kk(e.bundles==="import-url"),logger:e.logger?new Bx:void 0,storage:e.storage}),t)}function vv(...r){if(typeof r[0]=="string")return yv(r[0],r[1]);if(bk(r[0])){const{connection:t,client:e,...n}=r[0];if(e)return Aa(e,n);if(typeof t=="string")return yv(t,n);if(typeof t>"u")throw new Error("connection option is required");return Aa(TT({bundles:t.bundles,logger:t.logger,storage:t.storage}),n)}return Aa(r[0],r[1])}(r=>{function t(e){return Aa({options:{parsers:{},serializers:{}}},e)}r.mock=t})(vv||(vv={}));var Gh={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files diff --git a/assets/memory-long-term-BUwL0WhE.js b/assets/memory-long-term-C3e3nLW5.js similarity index 92% rename from assets/memory-long-term-BUwL0WhE.js rename to assets/memory-long-term-C3e3nLW5.js index 22a80bac27564946e6106949b571bbe07490de79..2f850fb5dcb0285770323966d6f961a73c9135e9 100644 --- a/assets/memory-long-term-BUwL0WhE.js +++ b/assets/memory-long-term-C3e3nLW5.js @@ -1 +1 @@ -import{d as r,bE as l,i as c,bw as d,A as m,o as p,c as u,a as t,e as o,D as n}from"./index-rD0Uu1v9.js";const _={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},x={relative:""},v={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},f={text:"neutral-300 dark:neutral-500","text-nowrap":""},g={"text-nowrap":"","text-3xl":"","font-semibold":""},h=r({__name:"memory-long-term",setup(y){const i=l(),{t:s}=c();return(b,e)=>{const a=d("motion");return m((p(),u("div",_,[t("button",{onClick:e[0]||(e[0]=w=>o(i).back())},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",x,[t("div",v,[t("span",f,n(o(s)("settings.title")),1)]),t("div",g,n(o(s)("settings.pages.modules.memory-long-term.title")),1)])])),[[a]])}}});export{h as default}; +import{d as r,bE as l,i as c,bw as d,A as m,o as p,c as u,a as t,e as o,D as n}from"./index-Dlp4W1Zl.js";const _={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},x={relative:""},v={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},f={text:"neutral-300 dark:neutral-500","text-nowrap":""},g={"text-nowrap":"","text-3xl":"","font-semibold":""},h=r({__name:"memory-long-term",setup(y){const i=l(),{t:s}=c();return(b,e)=>{const a=d("motion");return m((p(),u("div",_,[t("button",{onClick:e[0]||(e[0]=w=>o(i).back())},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",x,[t("div",v,[t("span",f,n(o(s)("settings.title")),1)]),t("div",g,n(o(s)("settings.pages.modules.memory-long-term.title")),1)])])),[[a]])}}});export{h as default}; diff --git a/assets/memory-short-term-C2rRGrUR.js b/assets/memory-short-term-r0JH0hk6.js similarity index 92% rename from assets/memory-short-term-C2rRGrUR.js rename to assets/memory-short-term-r0JH0hk6.js index 8fdebd449019e0690accda58371915b70b2e5fea..71eefa378b65344623c278e2572109039f67bf4e 100644 --- a/assets/memory-short-term-C2rRGrUR.js +++ b/assets/memory-short-term-r0JH0hk6.js @@ -1 +1 @@ -import{d as a,bE as l,i as c,bw as d,A as m,o as p,c as u,a as t,e as o,D as n}from"./index-rD0Uu1v9.js";const _={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},x={relative:""},v={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},f={text:"neutral-300 dark:neutral-500","text-nowrap":""},y={"text-nowrap":"","text-3xl":"","font-semibold":""},k=a({__name:"memory-short-term",setup(b){const i=l(),{t:s}=c();return(h,e)=>{const r=d("motion");return m((p(),u("div",_,[t("button",{onClick:e[0]||(e[0]=w=>o(i).back())},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",x,[t("div",v,[t("span",f,n(o(s)("settings.title")),1)]),t("div",y,n(o(s)("settings.pages.modules.memory-short-term.title")),1)])])),[[r]])}}});export{k as default}; +import{d as a,bE as l,i as c,bw as d,A as m,o as p,c as u,a as t,e as o,D as n}from"./index-Dlp4W1Zl.js";const _={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},x={relative:""},v={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},f={text:"neutral-300 dark:neutral-500","text-nowrap":""},y={"text-nowrap":"","text-3xl":"","font-semibold":""},k=a({__name:"memory-short-term",setup(b){const i=l(),{t:s}=c();return(h,e)=>{const r=d("motion");return m((p(),u("div",_,[t("button",{onClick:e[0]||(e[0]=w=>o(i).back())},e[1]||(e[1]=[t("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),t("h1",x,[t("div",v,[t("span",f,n(o(s)("settings.title")),1)]),t("div",y,n(o(s)("settings.pages.modules.memory-short-term.title")),1)])])),[[r]])}}});export{k as default}; diff --git a/assets/messages-CYVaGXcj.js b/assets/messages-CT9yvwKz.js similarity index 78% rename from assets/messages-CYVaGXcj.js rename to assets/messages-CT9yvwKz.js index 2705dfd727f7173019165185c02b633f7650a793..554f682221d880e2032e2ecbb487661fcb3270df 100644 --- a/assets/messages-CYVaGXcj.js +++ b/assets/messages-CT9yvwKz.js @@ -1 +1 @@ -import{u as m,_ as g,l as _}from"./queues-kGVt0l-U.js";import"./live2d-zip-loader-BdiFCiUD.js";import{d as v,g as t,c as l,o as u,a as e,b,e as x,D as c,bx as k,by as h}from"./index-rD0Uu1v9.js";import{u as z}from"./queue-EbaGahVd.js";const w={flex:"","flex-col":"","gap-2":"","p-2":""},y={flex:"","flex-row":"","gap-2":""},S={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},V={"w-full":"",flex:"","flex-row":"","gap-4":""},M={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},E=v({__name:"messages",setup(Q){const s=t(""),d=t([]),a=t(!1),f=z({handlers:[async i=>{d.value.push(i.data)}]}),r=m(f);async function p(){a.value=!0,r.add(s.value),r.add(_),s.value="",a.value=!1}return(i,n)=>(u(),l("div",w,[e("div",y,[b(x(g),{modelValue:s.value,"onUpdate:modelValue":n[0]||(n[0]=o=>s.value=o),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:p},null,8,["modelValue"]),e("button",S,c(a.value?"Processing...":"Send"),1)]),e("div",V,[e("div",M,[n[1]||(n[1]=e("h3",{"font-semibold":""}," TTS Message ",-1)),(u(!0),l(k,null,h(d.value,o=>(u(),l("div",{key:o},[e("div",null,c(o),1)]))),128))])])]))}});export{E as default}; +import{u as m,_ as g,l as _}from"./queues-CJq1hDiQ.js";import"./live2d-zip-loader-C5j9stxV.js";import{d as v,g as t,c as l,o as u,a as e,b,e as x,D as c,bx as k,by as h}from"./index-Dlp4W1Zl.js";import{u as z}from"./queue-DW8o1RLT.js";const w={flex:"","flex-col":"","gap-2":"","p-2":""},y={flex:"","flex-row":"","gap-2":""},S={"rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-4":""},V={"w-full":"",flex:"","flex-row":"","gap-4":""},M={"w-full":"","rounded-lg":"",bg:"zinc-100 dark:zinc-700","p-2":""},E=v({__name:"messages",setup(Q){const s=t(""),d=t([]),a=t(!1),f=z({handlers:[async i=>{d.value.push(i.data)}]}),r=m(f);async function p(){a.value=!0,r.add(s.value),r.add(_),s.value="",a.value=!1}return(i,n)=>(u(),l("div",w,[e("div",y,[b(x(g),{modelValue:s.value,"onUpdate:modelValue":n[0]||(n[0]=o=>s.value=o),placeholder:"Message",p:"2",bg:"zinc-100 dark:zinc-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:p},null,8,["modelValue"]),e("button",S,c(a.value?"Processing...":"Send"),1)]),e("div",V,[e("div",M,[n[1]||(n[1]=e("h3",{"font-semibold":""}," TTS Message ",-1)),(u(!0),l(k,null,h(d.value,o=>(u(),l("div",{key:o},[e("div",null,c(o),1)]))),128))])])]))}});export{E as default}; diff --git a/assets/microsoft-speech-CbKBRvT-.js b/assets/microsoft-speech-BPOz5ZLq.js similarity index 73% rename from assets/microsoft-speech-CbKBRvT-.js rename to assets/microsoft-speech-BPOz5ZLq.js index 5df3abba247293e67628be876d3aa765f6a3b426..76fa3a6750a0676fdc48859779f35337ceffa238 100644 --- a/assets/microsoft-speech-CbKBRvT-.js +++ b/assets/microsoft-speech-BPOz5ZLq.js @@ -1 +1 @@ -import{_ as P}from"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./live2d-zip-loader-BdiFCiUD.js";import{d as B,i as K,s as L,g as m,h as p,x as M,o as T,y as f,b as g,e as i}from"./index-rD0Uu1v9.js";import{u as q}from"./providers-Dg3FpvfZ.js";import{u as z}from"./speech-CUKri9wm.js";import{_ as E,a as F,b as G}from"./SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-UpCqB8UJ.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";import"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";const t="microsoft-speech",x="v1",ee=B({__name:"microsoft-speech",setup(H){const{t:h}=K(),U={pitch:0,speed:1,volume:0},r=z(),d=q(),{providers:n}=L(d),u=m(0),b=m(1),_=m(0),c=p({get:()=>{var o;return((o=n.value[t])==null?void 0:o.region)||"eastasia"},set:o=>{n.value[t]||(n.value[t]={}),n.value[t].region=o}}),C=p(()=>{var o;return!!((o=n.value[t])!=null&&o.apiKey)}),y=p(()=>r.availableVoices[t]||[]),k=p(()=>r.availableLanguages);async function $(o,e,a){const l=d.getProviderInstance(t);if(!l)throw new Error("Failed to initialize speech provider");const s=d.getProviderConfig(t),S=s.model||x,w={...s,region:c.value,disableSsml:!a};if(!a&&e){const V=y.value.find(v=>v.id===e);if(V){const v=r.generateSSML(o,V,{...s,pitch:u.value});return await r.speech(l,S,v,e,w)}}return await r.speech(l,S,o,e,w)}return(o,e)=>(T(),M(i(G),{"provider-id":t,"default-model":x,"additional-settings":U},{"basic-settings":f(()=>[g(i(P),{modelValue:c.value,"onUpdate:modelValue":e[0]||(e[0]=a=>c.value=a),label:i(h)("settings.pages.providers.provider.microsoft-speech.fields.field.region.label"),description:i(h)("settings.pages.providers.provider.microsoft-speech.fields.field.region.description"),placeholder:"eastasia",required:"",type:"text"},null,8,["modelValue","label","description"])]),"voice-settings":f(({voiceSettings:a,updateVoiceSettings:l})=>[g(i(F),{pitch:u.value,"onUpdate:pitch":e[1]||(e[1]=s=>u.value=s),speed:b.value,"onUpdate:speed":e[2]||(e[2]=s=>b.value=s),volume:_.value,"onUpdate:volume":e[3]||(e[3]=s=>_.value=s),settings:a,"show-pitch":!0,"show-speed":!0,"show-volume":!0,onUpdate:l},null,8,["pitch","speed","volume","settings","onUpdate"])]),playground:f(()=>[g(i(E),{"available-voices":y.value,"available-languages":k.value,"generate-speech":$,"api-key-configured":C.value,"default-text":"Hello! This is a test of the Microsoft Speech synthesis."},null,8,["available-voices","available-languages","api-key-configured"])]),_:1}))}});export{ee as default}; +import{_ as P}from"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./live2d-zip-loader-C5j9stxV.js";import{d as B,i as K,s as L,g as m,h as p,x as M,o as T,y as f,b as g,e as i}from"./index-Dlp4W1Zl.js";import{u as q}from"./providers-BRCa7xUS.js";import{u as z}from"./speech-DU07zXBj.js";import{_ as E,a as F,b as G}from"./SpeechVoiceSettings.vue_vue_type_script_setup_true_lang-CgsOdTr3.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";import"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";const t="microsoft-speech",x="v1",ee=B({__name:"microsoft-speech",setup(H){const{t:h}=K(),U={pitch:0,speed:1,volume:0},r=z(),d=q(),{providers:n}=L(d),u=m(0),b=m(1),_=m(0),c=p({get:()=>{var o;return((o=n.value[t])==null?void 0:o.region)||"eastasia"},set:o=>{n.value[t]||(n.value[t]={}),n.value[t].region=o}}),C=p(()=>{var o;return!!((o=n.value[t])!=null&&o.apiKey)}),y=p(()=>r.availableVoices[t]||[]),k=p(()=>r.availableLanguages);async function $(o,e,a){const l=d.getProviderInstance(t);if(!l)throw new Error("Failed to initialize speech provider");const s=d.getProviderConfig(t),S=s.model||x,w={...s,region:c.value,disableSsml:!a};if(!a&&e){const V=y.value.find(v=>v.id===e);if(V){const v=r.generateSSML(o,V,{...s,pitch:u.value});return await r.speech(l,S,v,e,w)}}return await r.speech(l,S,o,e,w)}return(o,e)=>(T(),M(i(G),{"provider-id":t,"default-model":x,"additional-settings":U},{"basic-settings":f(()=>[g(i(P),{modelValue:c.value,"onUpdate:modelValue":e[0]||(e[0]=a=>c.value=a),label:i(h)("settings.pages.providers.provider.microsoft-speech.fields.field.region.label"),description:i(h)("settings.pages.providers.provider.microsoft-speech.fields.field.region.description"),placeholder:"eastasia",required:"",type:"text"},null,8,["modelValue","label","description"])]),"voice-settings":f(({voiceSettings:a,updateVoiceSettings:l})=>[g(i(F),{pitch:u.value,"onUpdate:pitch":e[1]||(e[1]=s=>u.value=s),speed:b.value,"onUpdate:speed":e[2]||(e[2]=s=>b.value=s),volume:_.value,"onUpdate:volume":e[3]||(e[3]=s=>_.value=s),settings:a,"show-pitch":!0,"show-speed":!0,"show-volume":!0,onUpdate:l},null,8,["pitch","speed","volume","settings","onUpdate"])]),playground:f(()=>[g(i(E),{"available-voices":y.value,"available-languages":k.value,"generate-speech":$,"api-key-configured":C.value,"default-text":"Hello! This is a test of the Microsoft Speech synthesis."},null,8,["available-voices","available-languages","api-key-configured"])]),_:1}))}});export{ee as default}; diff --git a/assets/mistral-ai-BSvPWWKn.js b/assets/mistral-ai-C7perH7S.js similarity index 67% rename from assets/mistral-ai-BSvPWWKn.js rename to assets/mistral-ai-C7perH7S.js index 8b65f7713a79a6557a2583ab510d7d16badf3bef..c7fe4400d6300c5bd4010128e9bb9c7836fb2b0a 100644 --- a/assets/mistral-ai-BSvPWWKn.js +++ b/assets/mistral-ai-C7perH7S.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as U,i as V,bE as y,s as $,h as v,m as k,w as K,x as h,o as x,y as m,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="mistral-ai",H=U({__name:"mistral-ai",setup(S){const{t:p}=V(),_=y(),d=w(),{providers:o}=$(d),n=v(()=>d.getProviderMetadata(a)),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});k(()=>{var e,i;d.initializeProvider(a),s.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([s,r],()=>{o.value[a]={...o.value[a],apiKey:s.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return x(),h(t(R),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:m(()=>[l(t(N),null,{default:m(()=>[l(t(P),{title:t(p)("settings.pages.providers.common.section.basic.title"),description:t(p)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:m(()=>{var u;return[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=g=>s.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"mis-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(p)("settings.pages.providers.common.section.advanced.title")},{default:m(()=>[l(t(C),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=u=>r.value=u),placeholder:"https://api.mistral.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as U,i as V,bE as y,s as $,h as v,m as k,w as K,x as h,o as x,y as m,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="mistral-ai",H=U({__name:"mistral-ai",setup(S){const{t:p}=V(),_=y(),d=w(),{providers:o}=$(d),n=v(()=>d.getProviderMetadata(a)),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});k(()=>{var e,i;d.initializeProvider(a),s.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([s,r],()=>{o.value[a]={...o.value[a],apiKey:s.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return x(),h(t(R),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:m(()=>[l(t(N),null,{default:m(()=>[l(t(P),{title:t(p)("settings.pages.providers.common.section.basic.title"),description:t(p)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:m(()=>{var u;return[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=g=>s.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"mis-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(p)("settings.pages.providers.common.section.advanced.title")},{default:m(()=>[l(t(C),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=u=>r.value=u),placeholder:"https://api.mistral.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; diff --git a/assets/moonshot-ai-BpNd7lqk.js b/assets/moonshot-ai-CZlBN-5-.js similarity index 67% rename from assets/moonshot-ai-BpNd7lqk.js rename to assets/moonshot-ai-CZlBN-5-.js index 7f3a312c7aa163a7ea52443c477d6615f63bf2ec..f8c25bb2a9f8845f05e4172841c8ff7ac350379b 100644 --- a/assets/moonshot-ai-BpNd7lqk.js +++ b/assets/moonshot-ai-CZlBN-5-.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as h,i as U,bE as V,s as y,h as v,m as $,w as k,x as K,o as x,y as m,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="moonshot-ai",H=h({__name:"moonshot-ai",setup(B){const{t:p}=U(),_=V(),d=w(),{providers:o}=y(d),n=v(()=>d.getProviderMetadata(a)),i=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,s;d.initializeProvider(a),i.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((s=o.value[a])==null?void 0:s.baseUrl)||""}),k([i,r],()=>{o.value[a]={...o.value[a],apiKey:i.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,s)=>{var c,f;return x(),K(t(S),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:m(()=>[l(t(P),null,{default:m(()=>[l(t(R),{title:t(p)("settings.pages.providers.common.section.basic.title"),description:t(p)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:m(()=>{var u;return[l(t(N),{modelValue:i.value,"onUpdate:modelValue":s[0]||(s[0]=g=>i.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"ms-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(p)("settings.pages.providers.common.section.advanced.title")},{default:m(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":s[1]||(s[1]=u=>r.value=u),placeholder:"https://api.moonshot.cn/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as h,i as U,bE as V,s as y,h as v,m as $,w as k,x as K,o as x,y as m,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="moonshot-ai",H=h({__name:"moonshot-ai",setup(B){const{t:p}=U(),_=V(),d=w(),{providers:o}=y(d),n=v(()=>d.getProviderMetadata(a)),i=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,s;d.initializeProvider(a),i.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((s=o.value[a])==null?void 0:s.baseUrl)||""}),k([i,r],()=>{o.value[a]={...o.value[a],apiKey:i.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,s)=>{var c,f;return x(),K(t(S),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:m(()=>[l(t(P),null,{default:m(()=>[l(t(R),{title:t(p)("settings.pages.providers.common.section.basic.title"),description:t(p)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:m(()=>{var u;return[l(t(N),{modelValue:i.value,"onUpdate:modelValue":s[0]||(s[0]=g=>i.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"ms-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(p)("settings.pages.providers.common.section.advanced.title")},{default:m(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":s[1]||(s[1]=u=>r.value=u),placeholder:"https://api.moonshot.cn/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; diff --git a/assets/novita-ai-CMr47yM2.js b/assets/novita-ai-BTL9go8K.js similarity index 67% rename from assets/novita-ai-CMr47yM2.js rename to assets/novita-ai-BTL9go8K.js index 5b9da78d25aa0f12c96af7bbbb1af9f8e3a65888..60c45558a77efd7c049b7b8eaddc28b8b5ff025e 100644 --- a/assets/novita-ai-CMr47yM2.js +++ b/assets/novita-ai-BTL9go8K.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as U,i as V,bE as y,s as $,h as m,m as k,w as K,x as h,o as x,y as p,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="novita-ai",H=U({__name:"novita-ai",setup(S){const{t:d}=V(),_=y(),v=w(),{providers:o}=$(v),n=m(()=>v.getProviderMetadata(a)),s=m({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=m({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});k(()=>{var e,i;v.initializeProvider(a),s.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([s,r],()=>{o.value[a]={...o.value[a],apiKey:s.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return x(),h(t(R),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=g=>s.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"nvt-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=u=>r.value=u),placeholder:"https://api.novita.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as U,i as V,bE as y,s as $,h as m,m as k,w as K,x as h,o as x,y as p,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="novita-ai",H=U({__name:"novita-ai",setup(S){const{t:d}=V(),_=y(),v=w(),{providers:o}=$(v),n=m(()=>v.getProviderMetadata(a)),s=m({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=m({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});k(()=>{var e,i;v.initializeProvider(a),s.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([s,r],()=>{o.value[a]={...o.value[a],apiKey:s.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return x(),h(t(R),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=g=>s.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"nvt-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=u=>r.value=u),placeholder:"https://api.novita.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; diff --git a/assets/ollama-CxlTq2Yg.js b/assets/ollama-qKIKZqA2.js similarity index 88% rename from assets/ollama-CxlTq2Yg.js rename to assets/ollama-qKIKZqA2.js index 420399238974821511f9f0f034874c7f4c8e21db..2890f67ef8edc5738ee9a175e37d5eae0b6db802 100644 --- a/assets/ollama-CxlTq2Yg.js +++ b/assets/ollama-qKIKZqA2.js @@ -1 +1 @@ -import{_ as P}from"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";import{d as w,bF as x,bG as U,c as g,o as f,b as m,g as $,w as q,bw as N,a as _,A as D,bH as O,C as R,D as M,bx as S,by as z,i as F,bE as I,s as A,h as C,m as E,c6 as T,x as G,y as b,e as t}from"./index-rD0Uu1v9.js";import"./live2d-zip-loader-BdiFCiUD.js";import{u as H}from"./providers-Dg3FpvfZ.js";import{a as L,_ as j}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as J,a as Q}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as W}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";const X={flex:"~ gap-2"},Y=w({__name:"InputKeyValue",props:x({name:null,keyPlaceholder:null,valuePlaceholder:null},{propertyKey:{required:!0},propertyKeyModifiers:{},propertyValue:{required:!0},propertyValueModifiers:{}}),emits:["update:propertyKey","update:propertyValue"],setup(v){const o=v,s=U(v,"propertyKey"),u=U(v,"propertyValue");return(r,a)=>(f(),g("div",X,[m(P,{modelValue:s.value,"onUpdate:modelValue":a[0]||(a[0]=n=>s.value=n),placeholder:o.keyPlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"]),m(P,{modelValue:u.value,"onUpdate:modelValue":a[1]||(a[1]=n=>u.value=n),placeholder:o.valuePlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"])]))}}),Z={"max-w-full":""},ee={flex:"~ col gap-2"},le={class:"flex items-center gap-1 text-sm font-medium"},ae={key:0,class:"text-red-500"},te={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},oe={flex:"~ col gap-2"},re=["onClick"],se=w({__name:"FieldKeyValues",props:x({label:null,description:null,name:null,keyPlaceholder:null,valuePlaceholder:null,required:{type:Boolean},inputClass:null},{modelValue:{required:!0},modelModifiers:{}}),emits:x(["remove","add"],["update:modelValue"]),setup(v,{emit:o}){const s=v,u=o,r=U(v,"modelValue"),a=$(""),n=$("");return q([a,n],()=>{u("add",a.value,n.value)}),(K,p)=>{const k=N("auto-animate");return f(),g("div",Z,[_("label",ee,[_("div",null,[_("div",le,[O(M(s.label)+" ",1),s.required!==!1?(f(),g("span",ae,"*")):R("",!0)]),_("div",te,M(s.description),1)]),D((f(),g("div",oe,[(f(!0),g(S,null,z(r.value,(y,l)=>(f(),g("div",{key:l,"w-full":"",flex:"","items-center":"","gap-2":""},[m(Y,{"property-key":y.key,"onUpdate:propertyKey":e=>y.key=e,"property-value":y.value,"onUpdate:propertyValue":e=>y.value=e,"key-placeholder":s.keyPlaceholder,"value-placeholder":s.valuePlaceholder,"w-full":""},null,8,["property-key","onUpdate:propertyKey","property-value","onUpdate:propertyValue","key-placeholder","value-placeholder"]),_("button",{onClick:e=>u("remove",l)},p[0]||(p[0]=[_("div",{"i-solar:minus-circle-line-duotone":"",size:"6"},null,-1)]),8,re)]))),128))])),[[k]])])])}}}),d="ollama",_e=w({__name:"ollama",setup(v){const{t:o}=F(),s=I(),u=H(),{providers:r}=A(u),a=C(()=>u.getProviderMetadata(d)),n=C({get:()=>{var l,e,i;return((l=r.value[d])==null?void 0:l.baseUrl)||((i=(e=a.value)==null?void 0:e.defaultOptions)==null?void 0:i.baseUrl)||""},set:l=>{r.value[d]||(r.value[d]={}),r.value[d].baseUrl=l}});E(()=>{var l,e,i,h;u.initializeProvider(d),n.value=((l=r.value[d])==null?void 0:l.baseUrl)||((i=(e=a.value)==null?void 0:e.defaultOptions)==null?void 0:i.baseUrl)||"",(h=r.value[d])!=null&&h.headers||(r.value[d].headers={})});function K(){var l;r.value[d]={...(l=a.value)==null?void 0:l.defaultOptions}}const p=T([{key:"",value:""}]);function k(l,e,i){l&&l.push({key:e,value:i})}function y(l,e){e&&(e.length===1?(e[0].key="",e[0].value=""):e.splice(l,1))}return q(p,l=>{l.length>0&&(l[l.length-1].key!==""||l[l.length-1].value!=="")&&l.push({key:"",value:""})},{deep:!0,immediate:!0}),(l,e)=>{var i,h;return f(),G(t(W),{"provider-name":(i=a.value)==null?void 0:i.localizedName,"provider-icon":(h=a.value)==null?void 0:h.icon,"on-back":()=>t(s).back()},{default:b(()=>[m(t(J),null,{default:b(()=>[m(t(Q),{title:t(o)("settings.pages.providers.common.section.basic.title"),description:t(o)("settings.pages.providers.common.section.basic.description"),"on-reset":K},{default:b(()=>{var c,V;return[m(t(L),{modelValue:n.value,"onUpdate:modelValue":e[0]||(e[0]=B=>n.value=B),placeholder:((V=(c=a.value)==null?void 0:c.defaultOptions)==null?void 0:V.baseUrl)||"",required:""},null,8,["modelValue","placeholder"])]}),_:1},8,["title","description"]),m(t(j),{title:t(o)("settings.pages.providers.common.section.advanced.title")},{default:b(()=>[m(t(se),{modelValue:p,"onUpdate:modelValue":e[1]||(e[1]=c=>p=c),label:t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.label"),description:t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.description"),"key-placeholder":t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.key.placeholder"),"value-placeholder":t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.value.placeholder"),onAdd:e[2]||(e[2]=(c,V)=>k(p,c,V)),onRemove:e[3]||(e[3]=c=>y(c,p))},null,8,["modelValue","label","description","key-placeholder","value-placeholder"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{_e as default}; +import{_ as P}from"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";import{d as w,bF as x,bG as U,c as g,o as f,b as m,g as $,w as q,bw as N,a as _,A as D,bH as O,C as R,D as M,bx as S,by as z,i as F,bE as I,s as A,h as C,m as E,c6 as T,x as G,y as b,e as t}from"./index-Dlp4W1Zl.js";import"./live2d-zip-loader-C5j9stxV.js";import{u as H}from"./providers-BRCa7xUS.js";import{a as L,_ as j}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as J,a as Q}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as W}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";const X={flex:"~ gap-2"},Y=w({__name:"InputKeyValue",props:x({name:null,keyPlaceholder:null,valuePlaceholder:null},{propertyKey:{required:!0},propertyKeyModifiers:{},propertyValue:{required:!0},propertyValueModifiers:{}}),emits:["update:propertyKey","update:propertyValue"],setup(v){const o=v,s=U(v,"propertyKey"),u=U(v,"propertyValue");return(r,a)=>(f(),g("div",X,[m(P,{modelValue:s.value,"onUpdate:modelValue":a[0]||(a[0]=n=>s.value=n),placeholder:o.keyPlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"]),m(P,{modelValue:u.value,"onUpdate:modelValue":a[1]||(a[1]=n=>u.value=n),placeholder:o.valuePlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"])]))}}),Z={"max-w-full":""},ee={flex:"~ col gap-2"},le={class:"flex items-center gap-1 text-sm font-medium"},ae={key:0,class:"text-red-500"},te={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},oe={flex:"~ col gap-2"},re=["onClick"],se=w({__name:"FieldKeyValues",props:x({label:null,description:null,name:null,keyPlaceholder:null,valuePlaceholder:null,required:{type:Boolean},inputClass:null},{modelValue:{required:!0},modelModifiers:{}}),emits:x(["remove","add"],["update:modelValue"]),setup(v,{emit:o}){const s=v,u=o,r=U(v,"modelValue"),a=$(""),n=$("");return q([a,n],()=>{u("add",a.value,n.value)}),(K,p)=>{const k=N("auto-animate");return f(),g("div",Z,[_("label",ee,[_("div",null,[_("div",le,[O(M(s.label)+" ",1),s.required!==!1?(f(),g("span",ae,"*")):R("",!0)]),_("div",te,M(s.description),1)]),D((f(),g("div",oe,[(f(!0),g(S,null,z(r.value,(y,l)=>(f(),g("div",{key:l,"w-full":"",flex:"","items-center":"","gap-2":""},[m(Y,{"property-key":y.key,"onUpdate:propertyKey":e=>y.key=e,"property-value":y.value,"onUpdate:propertyValue":e=>y.value=e,"key-placeholder":s.keyPlaceholder,"value-placeholder":s.valuePlaceholder,"w-full":""},null,8,["property-key","onUpdate:propertyKey","property-value","onUpdate:propertyValue","key-placeholder","value-placeholder"]),_("button",{onClick:e=>u("remove",l)},p[0]||(p[0]=[_("div",{"i-solar:minus-circle-line-duotone":"",size:"6"},null,-1)]),8,re)]))),128))])),[[k]])])])}}}),d="ollama",_e=w({__name:"ollama",setup(v){const{t:o}=F(),s=I(),u=H(),{providers:r}=A(u),a=C(()=>u.getProviderMetadata(d)),n=C({get:()=>{var l,e,i;return((l=r.value[d])==null?void 0:l.baseUrl)||((i=(e=a.value)==null?void 0:e.defaultOptions)==null?void 0:i.baseUrl)||""},set:l=>{r.value[d]||(r.value[d]={}),r.value[d].baseUrl=l}});E(()=>{var l,e,i,h;u.initializeProvider(d),n.value=((l=r.value[d])==null?void 0:l.baseUrl)||((i=(e=a.value)==null?void 0:e.defaultOptions)==null?void 0:i.baseUrl)||"",(h=r.value[d])!=null&&h.headers||(r.value[d].headers={})});function K(){var l;r.value[d]={...(l=a.value)==null?void 0:l.defaultOptions}}const p=T([{key:"",value:""}]);function k(l,e,i){l&&l.push({key:e,value:i})}function y(l,e){e&&(e.length===1?(e[0].key="",e[0].value=""):e.splice(l,1))}return q(p,l=>{l.length>0&&(l[l.length-1].key!==""||l[l.length-1].value!=="")&&l.push({key:"",value:""})},{deep:!0,immediate:!0}),(l,e)=>{var i,h;return f(),G(t(W),{"provider-name":(i=a.value)==null?void 0:i.localizedName,"provider-icon":(h=a.value)==null?void 0:h.icon,"on-back":()=>t(s).back()},{default:b(()=>[m(t(J),null,{default:b(()=>[m(t(Q),{title:t(o)("settings.pages.providers.common.section.basic.title"),description:t(o)("settings.pages.providers.common.section.basic.description"),"on-reset":K},{default:b(()=>{var c,V;return[m(t(L),{modelValue:n.value,"onUpdate:modelValue":e[0]||(e[0]=B=>n.value=B),placeholder:((V=(c=a.value)==null?void 0:c.defaultOptions)==null?void 0:V.baseUrl)||"",required:""},null,8,["modelValue","placeholder"])]}),_:1},8,["title","description"]),m(t(j),{title:t(o)("settings.pages.providers.common.section.advanced.title")},{default:b(()=>[m(t(se),{modelValue:p,"onUpdate:modelValue":e[1]||(e[1]=c=>p=c),label:t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.label"),description:t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.description"),"key-placeholder":t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.key.placeholder"),"value-placeholder":t(o)("settings.pages.providers.common.section.advanced.fields.field.headers.value.placeholder"),onAdd:e[2]||(e[2]=(c,V)=>k(p,c,V)),onRemove:e[3]||(e[3]=c=>y(c,p))},null,8,["modelValue","label","description","key-placeholder","value-placeholder"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{_e as default}; diff --git a/assets/openai-aA-L1GVd.js b/assets/openai-BtuP56e_.js similarity index 68% rename from assets/openai-aA-L1GVd.js rename to assets/openai-BtuP56e_.js index 59bc0be8deab01ce2d1e202a4344faec9042486f..b415edbeee156f0f151999f8f3a57bfbb69dc16a 100644 --- a/assets/openai-aA-L1GVd.js +++ b/assets/openai-BtuP56e_.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as h,i as U,bE as V,s as k,h as v,m as y,w as $,x as K,o as x,y as p,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as I}from"./providers-Dg3FpvfZ.js";import{_ as w,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as R,a as S}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as z}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const e="openai",H=h({__name:"openai",setup(A){const{t:u}=U(),_=V(),c=I(),{providers:a}=k(c),m=v(()=>c.getProviderMetadata(e)),i=v({get:()=>{var o;return((o=a.value[e])==null?void 0:o.apiKey)||""},set:o=>{a.value[e]||(a.value[e]={}),a.value[e].apiKey=o}}),r=v({get:()=>{var o;return((o=a.value[e])==null?void 0:o.baseUrl)||"https://api.openai.com/v1/"},set:o=>{a.value[e]||(a.value[e]={}),a.value[e].baseUrl=o}});y(()=>{var o,s;a.value[e]||(a.value[e]={baseUrl:"https://api.openai.com/v1/"}),i.value=((o=a.value[e])==null?void 0:o.apiKey)||"",r.value=((s=a.value[e])==null?void 0:s.baseUrl)||"https://api.openai.com/v1/"}),$([i,r],()=>{a.value[e]={...a.value[e],apiKey:i.value,baseUrl:r.value||"https://api.openai.com/v1/"}});function b(){a.value[e]={baseUrl:"https://api.openai.com/v1/"}}return(o,s)=>{var d,f;return x(),K(t(z),{"provider-name":((d=m.value)==null?void 0:d.localizedName)||"OpenAI","provider-icon":(f=m.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(R),null,{default:p(()=>[l(t(S),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var n;return[l(t(N),{modelValue:i.value,"onUpdate:modelValue":s[0]||(s[0]=g=>i.value=g),"provider-name":((n=m.value)==null?void 0:n.localizedName)||"OpenAI",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(w),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":s[1]||(s[1]=n=>r.value=n),placeholder:"https://api.openai.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as h,i as U,bE as V,s as k,h as v,m as y,w as $,x as K,o as x,y as p,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as I}from"./providers-BRCa7xUS.js";import{_ as w,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as R,a as S}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as z}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const e="openai",H=h({__name:"openai",setup(A){const{t:u}=U(),_=V(),c=I(),{providers:a}=k(c),m=v(()=>c.getProviderMetadata(e)),i=v({get:()=>{var o;return((o=a.value[e])==null?void 0:o.apiKey)||""},set:o=>{a.value[e]||(a.value[e]={}),a.value[e].apiKey=o}}),r=v({get:()=>{var o;return((o=a.value[e])==null?void 0:o.baseUrl)||"https://api.openai.com/v1/"},set:o=>{a.value[e]||(a.value[e]={}),a.value[e].baseUrl=o}});y(()=>{var o,s;a.value[e]||(a.value[e]={baseUrl:"https://api.openai.com/v1/"}),i.value=((o=a.value[e])==null?void 0:o.apiKey)||"",r.value=((s=a.value[e])==null?void 0:s.baseUrl)||"https://api.openai.com/v1/"}),$([i,r],()=>{a.value[e]={...a.value[e],apiKey:i.value,baseUrl:r.value||"https://api.openai.com/v1/"}});function b(){a.value[e]={baseUrl:"https://api.openai.com/v1/"}}return(o,s)=>{var d,f;return x(),K(t(z),{"provider-name":((d=m.value)==null?void 0:d.localizedName)||"OpenAI","provider-icon":(f=m.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(R),null,{default:p(()=>[l(t(S),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var n;return[l(t(N),{modelValue:i.value,"onUpdate:modelValue":s[0]||(s[0]=g=>i.value=g),"provider-name":((n=m.value)==null?void 0:n.localizedName)||"OpenAI",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(w),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":s[1]||(s[1]=n=>r.value=n),placeholder:"https://api.openai.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; diff --git a/assets/openrouter-ai-DCnIiw2z.js b/assets/openrouter-ai-CCt-Li_l.js similarity index 70% rename from assets/openrouter-ai-DCnIiw2z.js rename to assets/openrouter-ai-CCt-Li_l.js index a8f604b42d7af57fcd44d3694802e56a5e098e5f..2de04a89a3afb5b4697ca8f163d36753b671aadc 100644 --- a/assets/openrouter-ai-DCnIiw2z.js +++ b/assets/openrouter-ai-CCt-Li_l.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as V,i as k,bE as y,s as $,h as _,m as K,w as O,x as h,o as x,y as v,b as d,e as s}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="openrouter-ai",J=V({__name:"openrouter-ai",setup(B){const{t:c}=k(),b=y(),f=w(),{providers:o}=$(f),l=_(()=>f.getProviderMetadata(a)),i=_({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),n=_({get:()=>{var e,t,r;return((e=o.value[a])==null?void 0:e.baseUrl)||((r=(t=l.value)==null?void 0:t.defaultOptions)==null?void 0:r.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});K(()=>{var e,t,r,u;f.initializeProvider(a),i.value=((e=o.value[a])==null?void 0:e.apiKey)||"",n.value=((t=o.value[a])==null?void 0:t.baseUrl)||((u=(r=l.value)==null?void 0:r.defaultOptions)==null?void 0:u.baseUrl)||""}),O([i,n],()=>{var e,t;o.value[a]={...o.value[a],apiKey:i.value,baseUrl:n.value||((t=(e=l.value)==null?void 0:e.defaultOptions)==null?void 0:t.baseUrl)||""}});function U(){var e;o.value[a]={...(e=l.value)==null?void 0:e.defaultOptions}}return(e,t)=>{var r,u;return x(),h(s(S),{"provider-name":(r=l.value)==null?void 0:r.localizedName,"provider-icon":(u=l.value)==null?void 0:u.icon,"on-back":()=>s(b).back()},{default:v(()=>[d(s(P),null,{default:v(()=>[d(s(R),{title:s(c)("settings.pages.providers.common.section.basic.title"),description:s(c)("settings.pages.providers.common.section.basic.description"),"on-reset":U},{default:v(()=>{var p;return[d(s(N),{modelValue:i.value,"onUpdate:modelValue":t[0]||(t[0]=m=>i.value=m),"provider-name":(p=l.value)==null?void 0:p.localizedName,placeholder:"sk-or-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),d(s(z),{title:s(c)("settings.pages.providers.common.section.advanced.title")},{default:v(()=>{var p,m;return[d(s(M),{modelValue:n.value,"onUpdate:modelValue":t[1]||(t[1]=g=>n.value=g),placeholder:((m=(p=l.value)==null?void 0:p.defaultOptions)==null?void 0:m.baseUrl)||""},null,8,["modelValue","placeholder"])]}),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{J as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as V,i as k,bE as y,s as $,h as _,m as K,w as O,x as h,o as x,y as v,b as d,e as s}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="openrouter-ai",J=V({__name:"openrouter-ai",setup(B){const{t:c}=k(),b=y(),f=w(),{providers:o}=$(f),l=_(()=>f.getProviderMetadata(a)),i=_({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),n=_({get:()=>{var e,t,r;return((e=o.value[a])==null?void 0:e.baseUrl)||((r=(t=l.value)==null?void 0:t.defaultOptions)==null?void 0:r.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});K(()=>{var e,t,r,u;f.initializeProvider(a),i.value=((e=o.value[a])==null?void 0:e.apiKey)||"",n.value=((t=o.value[a])==null?void 0:t.baseUrl)||((u=(r=l.value)==null?void 0:r.defaultOptions)==null?void 0:u.baseUrl)||""}),O([i,n],()=>{var e,t;o.value[a]={...o.value[a],apiKey:i.value,baseUrl:n.value||((t=(e=l.value)==null?void 0:e.defaultOptions)==null?void 0:t.baseUrl)||""}});function U(){var e;o.value[a]={...(e=l.value)==null?void 0:e.defaultOptions}}return(e,t)=>{var r,u;return x(),h(s(S),{"provider-name":(r=l.value)==null?void 0:r.localizedName,"provider-icon":(u=l.value)==null?void 0:u.icon,"on-back":()=>s(b).back()},{default:v(()=>[d(s(P),null,{default:v(()=>[d(s(R),{title:s(c)("settings.pages.providers.common.section.basic.title"),description:s(c)("settings.pages.providers.common.section.basic.description"),"on-reset":U},{default:v(()=>{var p;return[d(s(N),{modelValue:i.value,"onUpdate:modelValue":t[0]||(t[0]=m=>i.value=m),"provider-name":(p=l.value)==null?void 0:p.localizedName,placeholder:"sk-or-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),d(s(z),{title:s(c)("settings.pages.providers.common.section.advanced.title")},{default:v(()=>{var p,m;return[d(s(M),{modelValue:n.value,"onUpdate:modelValue":t[1]||(t[1]=g=>n.value=g),placeholder:((m=(p=l.value)==null?void 0:p.defaultOptions)==null?void 0:m.baseUrl)||""},null,8,["modelValue","placeholder"])]}),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{J as default}; diff --git a/assets/providers-BRCa7xUS.js b/assets/providers-BRCa7xUS.js new file mode 100644 index 0000000000000000000000000000000000000000..ff620508ea68f5f51528ff20a124804415f2dd6e --- /dev/null +++ b/assets/providers-BRCa7xUS.js @@ -0,0 +1 @@ +var oe=Object.defineProperty;var le=(a,r,t)=>r in a?oe(a,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[r]=t;var z=(a,r,t)=>le(a,typeof r!="symbol"?r+"":r,t);import{f as ce,cb as de,i as ue,g as q,w as pe,h as x}from"./index-Dlp4W1Zl.js";var T=class extends Error{constructor(r,t){super(r);z(this,"response");this.name="XSAIError",this.response=t}},me=a=>a.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`),k=a=>Object.fromEntries(Object.entries(a).map(([r,t])=>[me(r),t])),Q=a=>Object.fromEntries(Object.entries(a).filter(([,r])=>r!==void 0)),Me=a=>JSON.stringify(k(Q({...a,abortSignal:void 0,apiKey:void 0,baseURL:void 0,fetch:void 0,headers:void 0}))),Y=(a,r)=>Q({Authorization:r!==void 0?`Bearer ${r}`:void 0,...a}),R=(a,r)=>{const t=r.toString();return new URL(a,t.endsWith("/")?t:`${t}/`)},ge=async a=>{if(!a.ok){const r=new T(`Remote sent ${a.status} response`,a);throw r.cause=new Error(await a.text()),r}if(!a.body)throw new T("Response body is empty from remote server",a);if(!(a.body instanceof ReadableStream)){const r=new T(`Expected Response body to be a ReadableStream, but got ${String(a.body)}`,a);throw r.cause=new Error(`Content-Type is ${a.headers.get("Content-Type")}`),r}return a},ee=async a=>ge(a).then(async r=>r.json()),f=async a=>(a.fetch??globalThis.fetch)(R("models",a.baseURL),{headers:Y({"Content-Type":"application/json",...a.headers},a.apiKey),signal:a.abortSignal}).then(ee).then(({data:r})=>r),_=a=>({chat:r=>Object.assign(a,{model:r})}),M=a=>({embed:r=>Object.assign(a,{model:r})}),h=a=>({model:()=>a}),_e=a=>({speech:r=>Object.assign(a,{model:r})}),ve=a=>({transcription:r=>Object.assign(a,{model:r})}),p=(a,r)=>({metadata:{id:a,...r}}),u=(...a)=>Object.assign(a[0],...a.slice(1)),L=(a,r="https://api.deepseek.com/")=>u(p("deepseek"),_({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r})),$=(a,r="https://api.fireworks.ai/inference/v1/")=>u(p("fireworks"),_({apiKey:a,baseURL:r}),M({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r})),D=(a,r="https://api.mistral.ai/v1/")=>u(p("mistral"),_({apiKey:a,baseURL:r}),M({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r})),G=(a,r="https://api.moonshot.cn/v1/")=>u(p("moonshot"),_({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r})),N=(a,r="https://api.novita.ai/v3/openai/")=>u(p("novita"),_({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r})),H=(a,r="https://api.openai.com/v1/")=>u(p("openai"),_({apiKey:a,baseURL:r}),M({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r}),_e({apiKey:a,baseURL:r}),ve({apiKey:a,baseURL:r})),he=(a,r="")=>u(p("openrouter"),{chat:(t,o)=>{const v={apiKey:a,baseURL:r,model:t};return{...o?(({extraHeaders:d,models:y,provider:m})=>{d!=null&&(v.headers??(v.headers={}),Object.assign(v.headers,d));let c;return m!=null&&(c=k(m)),k({models:y,provider:c})})(o):{},...v}}},h({apiKey:a,baseURL:r})),fe=(a,r="https://api.perplexity.ai/")=>u(p("perplexity"),_({apiKey:a,baseURL:r})),V=(a,r="https://api.together.xyz/v1/")=>u(p("together-ai"),_({apiKey:a,baseURL:r}),M({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r,fetch:async(...t)=>globalThis.fetch(...t).then(async o=>o.json()).then(o=>Response.json({data:o,object:"list"}))})),ye=(a,r)=>{const t=`https://api.cloudflare.com/client/v4/accounts/${r}/ai/v1/`;return u(p("workers-ai"),_({apiKey:a,baseURL:t}),M({apiKey:a,baseURL:t}))},W=(a,r="https://api.x.ai/v1/")=>u(p("xai"),_({apiKey:a,baseURL:r}),h({apiKey:a,baseURL:r})),B=(a="http://localhost:11434/v1/")=>u(p("ollama"),_({baseURL:a}),M({baseURL:a}),h({baseURL:a}));function J(a,r="http://localhost:5933/v1/"){const t=({applyTextNormalization:n,languageCode:d,nextRequestIds:y,nextText:m,previousRequestIds:c,previousText:P,pronunciationDictionaryLocators:w,seed:K,voiceSettings:E})=>({extraBody:k({applyTextNormalization:n,languageCode:d,nextRequestIds:y,nextText:m,previousRequestIds:c,previousText:P,pronunciationDictionaryLocators:w?w.map(C=>k(C)):void 0,seed:K,voiceSettings:E!=null?k(E):{similarityBoost:.75,stability:.5}})});return u({speech:(n,d)=>({...d?t(d):{},apiKey:a,baseURL:r,model:`elevenlabs/${n}`})},{voice:n=>(r.endsWith("v1/")?r=r.slice(0,-3):r.endsWith("v1")&&(r=r.slice(0,-2)),{query:"provider=elevenlabs",...n?t(n):{},apiKey:a,baseURL:r})})}async function X(a){return(a.fetch??globalThis.fetch)(R(a.query?`api/voices?${a.query}`:"api/voices",a.baseURL),{headers:Y({...a.headers},a.apiKey),method:"GET",signal:a.abortSignal}).then(ee).then(({voices:r})=>r)}function Z(a,r="http://localhost:5933/v1/"){const t=n=>{const{deploymentId:d,region:y,sampleRate:m}=n,c={deploymentId:d,region:y,sampleRate:m};return"disableSsml"in n?c.disableSsml=n.disableSsml:"lang"in n&&(c.lang=n.lang,c.gender=n.gender,c.voice=n.voice),{extraBody:k(c)}};return u({speech:(n,d)=>({...d?t(d):{},apiKey:a,baseURL:r,model:`microsoft/${n}`})},{voice:n=>(r.endsWith("v1/")?r=r.slice(0,-3):r.endsWith("v1")&&(r=r.slice(0,-2)),{query:`region=${n==null?void 0:n.region}&provider=microsoft`,...n?t(n):{},apiKey:a,baseURL:r})})}const be=[{model_id:"eleven_multilingual_v2",name:"Eleven Multilingual v2",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!0,can_use_speaker_boost:!0,serves_pro_voices:!1,token_cost_factor:1,description:"Our most life-like, emotionally rich mode in 29 languages. Best for voice overs, audiobooks, post-production, or any other content creation needs.",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"},{language_id:"ru",name:"Russian"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_flash_v2_5",name:"Eleven Flash v2.5",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our ultra low latency model in 32 languages. Ideal for conversational use cases.",requires_alpha_access:!1,max_characters_request_free_user:4e4,max_characters_request_subscribed_user:4e4,maximum_text_length_per_request:4e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"ru",name:"Russian"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"},{language_id:"hu",name:"Hungarian"},{language_id:"no",name:"Norwegian"},{language_id:"vi",name:"Vietnamese"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_turbo_v2_5",name:"Eleven Turbo v2.5",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our high quality, low latency model in 32 languages. Best for developer use cases where speed matters and you need non-English languages.",requires_alpha_access:!1,max_characters_request_free_user:4e4,max_characters_request_subscribed_user:4e4,maximum_text_length_per_request:4e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"ru",name:"Russian"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"},{language_id:"vi",name:"Vietnamese"},{language_id:"no",name:"Norwegian"},{language_id:"hu",name:"Hungarian"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_turbo_v2",name:"Eleven Turbo v2",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our English-only, low latency model. Best for developer use cases where speed matters and you only need English. Performance is on par with Turbo v2.5.",requires_alpha_access:!1,max_characters_request_free_user:3e4,max_characters_request_subscribed_user:3e4,maximum_text_length_per_request:3e4,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_flash_v2",name:"Eleven Flash v2",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our ultra low latency model in english. Ideal for conversational use cases.",requires_alpha_access:!1,max_characters_request_free_user:3e4,max_characters_request_subscribed_user:3e4,maximum_text_length_per_request:3e4,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_english_sts_v2",name:"Eleven English v2",can_be_finetuned:!1,can_do_text_to_speech:!1,can_do_voice_conversion:!0,can_use_style:!0,can_use_speaker_boost:!0,serves_pro_voices:!1,token_cost_factor:1,description:"Our state-of-the-art speech to speech model suitable for scenarios where you need maximum control over the content and prosody of your generations.",requires_alpha_access:!1,max_characters_request_free_user:5e3,max_characters_request_subscribed_user:5e3,maximum_text_length_per_request:5e3,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_multilingual_v1",name:"Eleven Multilingual v1",can_be_finetuned:!1,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our first Multilingual model, capability of generating speech in 10 languages. Now outclassed by Multilingual v2 (for content creation) and Turbo v2.5 (for low latency use cases).",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"},{language_id:"de",name:"German"},{language_id:"pl",name:"Polish"},{language_id:"es",name:"Spanish"},{language_id:"it",name:"Italian"},{language_id:"fr",name:"French"},{language_id:"pt",name:"Portuguese"},{language_id:"hi",name:"Hindi"},{language_id:"ar",name:"Arabic"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_multilingual_sts_v2",name:"Eleven Multilingual v2",can_be_finetuned:!0,can_do_text_to_speech:!1,can_do_voice_conversion:!0,can_use_style:!0,can_use_speaker_boost:!0,serves_pro_voices:!1,token_cost_factor:1,description:"Our cutting-edge, multilingual speech-to-speech model is designed for situations that demand unparalleled control over both the content and the prosody of the generated speech across various languages.",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"ru",name:"Russian"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_monolingual_v1",name:"Eleven English v1",can_be_finetuned:!1,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our first ever text to speech model. Now outclassed by Multilingual v2 (for content creation) and Turbo v2.5 (for low latency use cases).",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"}],Pe=ce("providers",()=>{const a=de("settings/credentials/providers",{}),{t:r}=ue();async function t(e){try{const i=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e.apiKey.trim()}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch OpenRouter models: ${i.statusText}`);return(await i.json()).data.map(s=>({id:s.id,name:s.name||s.id,provider:"openrouter-ai",description:s.description||"",contextLength:s.context_length,deprecated:!1}))}catch(i){throw console.error("Error fetching OpenRouter models:",i),i}}const o={"openrouter-ai":{id:"openrouter-ai",nameKey:"settings.pages.providers.provider.openrouter.title",name:"OpenRouter",descriptionKey:"settings.pages.providers.provider.openrouter.description",description:"openrouter.ai",icon:"i-lobe-icons:openrouter",defaultOptions:{baseUrl:"https://openrouter.ai/api/v1/"},createProvider:e=>he(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>t(e)}},openai:{id:"openai",nameKey:"settings.pages.providers.provider.openai.title",name:"OpenAI",descriptionKey:"settings.pages.providers.provider.openai.description",description:"openai.com",icon:"i-lobe-icons:openai",defaultOptions:{baseUrl:"https://api.openai.com/v1/"},createProvider:e=>H(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...H(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"openai",description:"",contextLength:0,deprecated:!1}))}},ollama:{id:"ollama",nameKey:"settings.pages.providers.provider.ollama.title",name:"Ollama",descriptionKey:"settings.pages.providers.provider.ollama.description",description:"ollama.com",icon:"i-lobe-icons:ollama",defaultOptions:{baseUrl:"http://localhost:11434/api/"},createProvider:e=>B(e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...B(e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"ollama",description:"",contextLength:0,deprecated:!1}))}},vllm:{id:"vllm",nameKey:"settings.pages.providers.provider.vllm.title",name:"vLLM",descriptionKey:"settings.pages.providers.provider.vllm.description",description:"vllm.ai",iconColor:"i-lobe-icons:vllm-color",createProvider:e=>B(e.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"llama-2-7b",name:"Llama 2 (7B)",provider:"vllm",description:"Meta's Llama 2 7B parameter model",contextLength:4096},{id:"llama-2-13b",name:"Llama 2 (13B)",provider:"vllm",description:"Meta's Llama 2 13B parameter model",contextLength:4096},{id:"llama-2-70b",name:"Llama 2 (70B)",provider:"vllm",description:"Meta's Llama 2 70B parameter model",contextLength:4096},{id:"mistral-7b",name:"Mistral (7B)",provider:"vllm",description:"Mistral AI's 7B parameter model",contextLength:8192},{id:"mixtral-8x7b",name:"Mixtral (8x7B)",provider:"vllm",description:"Mistral AI's Mixtral 8x7B MoE model",contextLength:32768},{id:"custom",name:"Custom Model",provider:"vllm",description:"Specify a custom model name",contextLength:0}]}},"perplexity-ai":{id:"perplexity-ai",nameKey:"settings.pages.providers.provider.perplexity.title",name:"Perplexity",descriptionKey:"settings.pages.providers.provider.perplexity.description",description:"perplexity.ai",icon:"i-lobe-icons:perplexity",defaultOptions:{baseUrl:"https://api.perplexity.ai"},createProvider:e=>fe(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"sonar-small-online",name:"Sonar Small (Online)",provider:"perplexity-ai",description:"Efficient model with online search capabilities",contextLength:12e3},{id:"sonar-medium-online",name:"Sonar Medium (Online)",provider:"perplexity-ai",description:"Balanced model with online search capabilities",contextLength:12e3},{id:"sonar-large-online",name:"Sonar Large (Online)",provider:"perplexity-ai",description:"Powerful model with online search capabilities",contextLength:12e3},{id:"codey-small",name:"Codey Small",provider:"perplexity-ai",description:"Specialized for code generation and understanding",contextLength:12e3},{id:"codey-large",name:"Codey Large",provider:"perplexity-ai",description:"Advanced code generation and understanding",contextLength:12e3}]}},elevenlabs:{id:"elevenlabs",nameKey:"settings.pages.providers.provider.elevenlabs.title",name:"ElevenLabs",descriptionKey:"settings.pages.providers.provider.elevenlabs.description",description:"elevenlabs.io",icon:"i-simple-icons:elevenlabs",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/",voiceSettings:{similarityBoost:.75,stability:.5}},createProvider:e=>J(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async()=>be.map(e=>({id:e.model_id,name:e.name,provider:"elevenlabs",description:e.description,contextLength:0,deprecated:!1})),listVoices:async e=>{const i=J(e.apiKey.trim(),e.baseUrl.trim()),l=await X({...i.voice()}),s=l.findIndex(b=>b.name.includes("Aria")),g=l.findIndex(b=>b.name.includes("Bill")),A=s!==-1?s:0,U=g!==-1?g:l.length-1,F=Math.min(A,U),I=Math.max(A,U);return[...l.slice(0,F),...l.slice(I+1),...l.slice(F,I+1)].map(b=>({id:b.id,name:b.name,provider:"elevenlabs",previewURL:b.preview_audio_url,languages:b.languages}))}}},xai:{id:"xai",nameKey:"settings.pages.providers.provider.xai.title",name:"xAI",descriptionKey:"settings.pages.providers.provider.xai.description",description:"x.ai",icon:"i-lobe-icons:xai",createProvider:e=>W(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...W(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"xai",description:"",contextLength:0,deprecated:!1}))}},deepseek:{id:"deepseek",nameKey:"settings.pages.providers.provider.deepseek.title",name:"DeepSeek",descriptionKey:"settings.pages.providers.provider.deepseek.description",description:"deepseek.com",iconColor:"i-lobe-icons:deepseek-color",createProvider:e=>L(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...L(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"deepseek",description:"",contextLength:0,deprecated:!1}))}},"together-ai":{id:"together-ai",nameKey:"settings.pages.providers.provider.together.title",name:"Together.ai",descriptionKey:"settings.pages.providers.provider.together.description",description:"together.ai",iconColor:"i-lobe-icons:together-color",createProvider:e=>V(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...V(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"together-ai",description:"",contextLength:0,deprecated:!1}))}},"novita-ai":{id:"novita-ai",nameKey:"settings.pages.providers.provider.novita.title",name:"Novita",descriptionKey:"settings.pages.providers.provider.novita.description",description:"novita.ai",iconColor:"i-lobe-icons:novita-color",createProvider:e=>N(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...N(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"novita-ai",description:"",contextLength:0,deprecated:!1}))}},"fireworks-ai":{id:"fireworks-ai",nameKey:"settings.pages.providers.provider.fireworks.title",name:"Fireworks.ai",descriptionKey:"settings.pages.providers.provider.fireworks.description",description:"fireworks.ai",icon:"i-lobe-icons:fireworks",createProvider:e=>$(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...$(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"fireworks-ai",description:"",contextLength:0,deprecated:!1}))}},"microsoft-speech":{id:"microsoft-speech",nameKey:"settings.pages.providers.provider.microsoft-speech.title",name:"Microsoft / Azure Speech",descriptionKey:"settings.pages.providers.provider.microsoft-speech.description",description:"speech.microsoft.com",iconColor:"i-lobe-icons:microsoft-color",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>Z(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"v1",name:"v1",provider:"microsoft-speech",description:"",contextLength:0,deprecated:!1}],listVoices:async e=>{const i=Z(e.apiKey.trim(),e.baseUrl.trim());return(await X({...i.voice({region:e.region})})).map(s=>{var g;return{id:s.id,name:s.name,provider:"microsoft-speech",previewURL:s.preview_audio_url,languages:s.languages,gender:(g=s.labels)==null?void 0:g.gender}})}}},"cloudflare-workers-ai":{id:"cloudflare-workers-ai",nameKey:"settings.pages.providers.provider.cloudflare-workers-ai.title",name:"Cloudflare Workers AI",descriptionKey:"settings.pages.providers.provider.cloudflare-workers-ai.description",description:"cloudflare.com",iconColor:"i-lobe-icons:cloudflare-color",createProvider:e=>ye(e.apiKey.trim(),e.accountId),capabilities:{listModels:async()=>[]}},"mistral-ai":{id:"mistral-ai",nameKey:"settings.pages.providers.provider.mistral.title",name:"Mistral",descriptionKey:"settings.pages.providers.provider.mistral.description",description:"mistral.ai",iconColor:"i-lobe-icons:mistral-color",createProvider:e=>D(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...D(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"mistral-ai",description:"",contextLength:0,deprecated:!1}))}},"moonshot-ai":{id:"moonshot-ai",nameKey:"settings.pages.providers.provider.moonshot.title",name:"Moonshot AI",descriptionKey:"settings.pages.providers.provider.moonshot.description",description:"moonshot.ai",icon:"i-lobe-icons:moonshot",createProvider:e=>G(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await f({...G(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"moonshot-ai",description:"",contextLength:0,deprecated:!1}))}}};function v(e){const i=a.value[e];if(!i)return!1;switch(e){case"openrouter-ai":return!!i.apiKey&&!!i.baseUrl;case"openai":return!!i.apiKey;case"ollama":return!!i.baseUrl;case"vllm":return!!i.baseUrl;case"elevenlabs":return!!i.apiKey;case"xai":return!!i.apiKey;case"deepseek":return!!i.apiKey;case"together-ai":return!!i.apiKey;case"novita-ai":return!!i.apiKey;case"fireworks-ai":return!!i.apiKey;case"microsoft-speech":return!!i.apiKey&&!!i.region;case"cloudflare-workers-ai":return!!i.apiKey;case"mistral-ai":return!!i.apiKey;case"moonshot-ai":return!!i.apiKey;default:return!1}}const n=q({});function d(e){var i;if(!a.value[e]){const l=o[e];a.value[e]={baseUrl:((i=l.defaultOptions)==null?void 0:i.baseUrl)||""}}}Object.keys(o).forEach(d);function y(){Object.keys(o).forEach(e=>{n.value[e]=v(e)})}y(),pe(a,y,{deep:!0});const m=x(()=>Object.keys(o).filter(e=>n.value[e])),c=q({}),P=q({}),w=q({});async function K(e){const i=a.value[e];if(!i)return[];const l=o[e];if(!l)return[];P.value[e]=!0,w.value[e]=null;try{const s=l.capabilities.listModels?await l.capabilities.listModels(i):[];return c.value[e]=s.map(g=>({id:g.id,name:g.name,description:g.description,contextLength:g.contextLength,deprecated:g.deprecated,provider:e})),c.value[e]}catch(s){return console.error(`Error fetching models for ${e}:`,s),w.value[e]=s instanceof Error?s.message:"Unknown error",[]}finally{P.value[e]=!1}}function E(e){return c.value[e]||[]}const C=x(()=>{const e=[];for(const i of m.value)e.push(...c.value[i]||[]);return e});async function ae(){for(const e of m.value)o[e].capabilities.listModels&&await K(e)}function j(e){const i=o[e];if(!i)throw new Error(`Provider metadata for ${e} not found`);return{...i,localizedName:r(i.nameKey,i.name),localizedDescription:r(i.descriptionKey,i.description)}}const re=x(()=>Object.values(o).map(e=>({...e,localizedName:r(e.nameKey,e.name),localizedDescription:r(e.descriptionKey,e.description),configured:n.value[e.id]||!1})));function O(e){const i=a.value[e];if(!i)throw new Error(`Provider credentials for ${e} not found`);const l=o[e];if(!l)throw new Error(`Provider metadata for ${e} not found`);try{return l.createProvider(i)}catch(s){throw console.error(`Error creating provider instance for ${e}:`,s),s}}const S=x(()=>m.value.map(e=>j(e))),ie=x(()=>S.value.filter(e=>{const i=O(e.id);return"chat"in i&&typeof i.chat=="function"})),ne=x(()=>S.value.filter(e=>{const i=O(e.id);return"transcription"in i&&typeof i.transcription=="function"})),te=x(()=>S.value.filter(e=>{const i=O(e.id);return"speech"in i&&typeof i.speech=="function"}));function se(e){return a.value[e]}return{providers:a,getProviderConfig:se,availableProviders:m,configuredProviders:n,providerMetadata:o,getProviderMetadata:j,allProvidersMetadata:re,initializeProvider:d,validateProvider:v,availableModels:c,isLoadingModels:P,modelLoadError:w,fetchModelsForProvider:K,getModelsForProvider:E,allAvailableModels:C,loadModelsForConfiguredProviders:ae,getProviderInstance:O,availableProvidersMetadata:S,availableTextGenerationsProvidersMetadata:ie,availableAudioSpeechProvidersMetadata:te,availableAudioTranscriptionProvidersMetadata:ne}});export{Y as a,Me as b,Q as c,ge as d,f as l,R as r,Pe as u}; diff --git a/assets/providers-Dg3FpvfZ.js b/assets/providers-Dg3FpvfZ.js deleted file mode 100644 index c255b2f26ded8c116971b730e8a092d604738b5b..0000000000000000000000000000000000000000 --- a/assets/providers-Dg3FpvfZ.js +++ /dev/null @@ -1 +0,0 @@ -var oe=Object.defineProperty;var le=(e,r,n)=>r in e?oe(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;var j=(e,r,n)=>le(e,typeof r!="symbol"?r+"":r,n);import{f as ce,cb as de,i as ue,g as O,w as pe,h as x}from"./index-rD0Uu1v9.js";var T=class extends Error{constructor(n,o){super(n);j(this,"response");this.name="XSAIError",this.response=o}},me=e=>e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`),B=e=>Object.fromEntries(Object.entries(e).map(([r,n])=>[me(r),n])),Y=e=>Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),$e=e=>JSON.stringify(B(Y({...e,abortSignal:void 0,apiKey:void 0,baseURL:void 0,fetch:void 0,headers:void 0}))),ge=(e,r)=>Y({Authorization:r!==void 0?`Bearer ${r}`:void 0,...e}),_e=(e,r)=>{const n=r.toString();return new URL(e,n.endsWith("/")?n:`${n}/`)},ve=async e=>{if(!e.ok){const r=new T(`Remote sent ${e.status} response`,e);throw r.cause=new Error(await e.text()),r}if(!e.body)throw new T("Response body is empty from remote server",e);if(!(e.body instanceof ReadableStream)){const r=new T(`Expected Response body to be a ReadableStream, but got ${String(e.body)}`,e);throw r.cause=new Error(`Content-Type is ${e.headers.get("Content-Type")}`),r}return e},he=async e=>ve(e).then(async r=>r.json()),f=async e=>(e.fetch??globalThis.fetch)(_e("models",e.baseURL),{headers:ge({"Content-Type":"application/json",...e.headers},e.apiKey),signal:e.abortSignal}).then(he).then(({data:r})=>r),_=e=>({chat:r=>Object.assign(e,{model:r})}),k=e=>({embed:r=>Object.assign(e,{model:r})}),h=e=>({model:()=>e}),fe=e=>({speech:r=>Object.assign(e,{model:r})}),ye=e=>({transcription:r=>Object.assign(e,{model:r})}),u=(e,r)=>({metadata:{id:e,...r}}),p=(...e)=>Object.assign(e[0],...e.slice(1)),D=(e,r="https://api.deepseek.com/")=>p(u("deepseek"),_({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r})),G=(e,r="https://api.fireworks.ai/inference/v1/")=>p(u("fireworks"),_({apiKey:e,baseURL:r}),k({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r})),N=(e,r="https://api.mistral.ai/v1/")=>p(u("mistral"),_({apiKey:e,baseURL:r}),k({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r})),H=(e,r="https://api.moonshot.cn/v1/")=>p(u("moonshot"),_({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r})),W=(e,r="https://api.novita.ai/v3/openai/")=>p(u("novita"),_({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r})),J=(e,r="https://api.openai.com/v1/")=>p(u("openai"),_({apiKey:e,baseURL:r}),k({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r}),fe({apiKey:e,baseURL:r}),ye({apiKey:e,baseURL:r})),be=(e,r="")=>p(u("openrouter"),{chat:(n,o)=>{const v={apiKey:e,baseURL:r,model:n};return{...o?(({extraHeaders:d,models:y,provider:m})=>{d!=null&&(v.headers??(v.headers={}),Object.assign(v.headers,d));let c;return m!=null&&(c=B(m)),B({models:y,provider:c})})(o):{},...v}}},h({apiKey:e,baseURL:r})),xe=(e,r="https://api.perplexity.ai/")=>p(u("perplexity"),_({apiKey:e,baseURL:r})),V=(e,r="https://api.together.xyz/v1/")=>p(u("together-ai"),_({apiKey:e,baseURL:r}),k({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r,fetch:async(...n)=>globalThis.fetch(...n).then(async o=>o.json()).then(o=>Response.json({data:o,object:"list"}))})),we=(e,r)=>{const n=`https://api.cloudflare.com/client/v4/accounts/${r}/ai/v1/`;return p(u("workers-ai"),_({apiKey:e,baseURL:n}),k({apiKey:e,baseURL:n}))},X=(e,r="https://api.x.ai/v1/")=>p(u("xai"),_({apiKey:e,baseURL:r}),h({apiKey:e,baseURL:r})),$=(e="http://localhost:11434/v1/")=>p(u("ollama"),_({baseURL:e}),k({baseURL:e}),h({baseURL:e})),ee=(...e)=>Object.assign(e[0],...e.slice(1)),A=class extends Error{constructor(r,n){super(r);j(this,"response");this.name="XSAIError",this.response=n}},ke=e=>e.replace(/[A-Z]/g,r=>`_${r.toLowerCase()}`),q=e=>Object.fromEntries(Object.entries(e).map(([r,n])=>[ke(r),n])),Me=e=>Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),Pe=(e,r)=>Me({Authorization:r!==void 0?`Bearer ${r}`:void 0,...e}),Se=(e,r)=>{const n=r.toString();return new URL(e,n.endsWith("/")?n:`${n}/`)},Ee=async e=>{if(!e.ok){const r=new A(`Remote sent ${e.status} response`,e);throw r.cause=new Error(await e.text()),r}if(!e.body)throw new A("Response body is empty from remote server",e);if(!(e.body instanceof ReadableStream)){const r=new A(`Expected Response body to be a ReadableStream, but got ${String(e.body)}`,e);throw r.cause=new Error(`Content-Type is ${e.headers.get("Content-Type")}`),r}return e},Ke=async e=>Ee(e).then(async r=>r.json());function R(e,r="http://localhost:5933/v1/"){const n=({applyTextNormalization:t,languageCode:d,nextRequestIds:y,nextText:m,previousRequestIds:c,previousText:M,pronunciationDictionaryLocators:w,seed:P,voiceSettings:S})=>({extraBody:q({applyTextNormalization:t,languageCode:d,nextRequestIds:y,nextText:m,previousRequestIds:c,previousText:M,pronunciationDictionaryLocators:w?w.map(C=>q(C)):void 0,seed:P,voiceSettings:S!=null?q(S):{similarityBoost:.75,stability:.5}})});return ee({speech:(t,d)=>({...d?n(d):{},apiKey:e,baseURL:r,model:`elevenlabs/${t}`})},{voice:t=>(r.endsWith("v1/")?r=r.slice(0,-3):r.endsWith("v1")&&(r=r.slice(0,-2)),{query:"provider=elevenlabs",...t?n(t):{},apiKey:e,baseURL:r})})}async function Z(e){return(e.fetch??globalThis.fetch)(Se(e.query?`api/voices?${e.query}`:"api/voices",e.baseURL),{headers:Pe({...e.headers},e.apiKey),method:"GET",signal:e.abortSignal}).then(Ke).then(({voices:r})=>r)}function Q(e,r="http://localhost:5933/v1/"){const n=t=>{const{deploymentId:d,region:y,sampleRate:m}=t,c={deploymentId:d,region:y,sampleRate:m};return"disableSsml"in t?c.disableSsml=t.disableSsml:"lang"in t&&(c.lang=t.lang,c.gender=t.gender,c.voice=t.voice),{extraBody:q(c)}};return ee({speech:(t,d)=>({...d?n(d):{},apiKey:e,baseURL:r,model:`microsoft/${t}`})},{voice:t=>(r.endsWith("v1/")?r=r.slice(0,-3):r.endsWith("v1")&&(r=r.slice(0,-2)),{query:`region=${t==null?void 0:t.region}&provider=microsoft`,...t?n(t):{},apiKey:e,baseURL:r})})}const Oe=[{model_id:"eleven_multilingual_v2",name:"Eleven Multilingual v2",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!0,can_use_speaker_boost:!0,serves_pro_voices:!1,token_cost_factor:1,description:"Our most life-like, emotionally rich mode in 29 languages. Best for voice overs, audiobooks, post-production, or any other content creation needs.",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"},{language_id:"ru",name:"Russian"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_flash_v2_5",name:"Eleven Flash v2.5",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our ultra low latency model in 32 languages. Ideal for conversational use cases.",requires_alpha_access:!1,max_characters_request_free_user:4e4,max_characters_request_subscribed_user:4e4,maximum_text_length_per_request:4e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"ru",name:"Russian"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"},{language_id:"hu",name:"Hungarian"},{language_id:"no",name:"Norwegian"},{language_id:"vi",name:"Vietnamese"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_turbo_v2_5",name:"Eleven Turbo v2.5",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our high quality, low latency model in 32 languages. Best for developer use cases where speed matters and you need non-English languages.",requires_alpha_access:!1,max_characters_request_free_user:4e4,max_characters_request_subscribed_user:4e4,maximum_text_length_per_request:4e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"ru",name:"Russian"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"},{language_id:"vi",name:"Vietnamese"},{language_id:"no",name:"Norwegian"},{language_id:"hu",name:"Hungarian"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_turbo_v2",name:"Eleven Turbo v2",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our English-only, low latency model. Best for developer use cases where speed matters and you only need English. Performance is on par with Turbo v2.5.",requires_alpha_access:!1,max_characters_request_free_user:3e4,max_characters_request_subscribed_user:3e4,maximum_text_length_per_request:3e4,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_flash_v2",name:"Eleven Flash v2",can_be_finetuned:!0,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our ultra low latency model in english. Ideal for conversational use cases.",requires_alpha_access:!1,max_characters_request_free_user:3e4,max_characters_request_subscribed_user:3e4,maximum_text_length_per_request:3e4,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:.5},concurrency_group:"turbo"},{model_id:"eleven_english_sts_v2",name:"Eleven English v2",can_be_finetuned:!1,can_do_text_to_speech:!1,can_do_voice_conversion:!0,can_use_style:!0,can_use_speaker_boost:!0,serves_pro_voices:!1,token_cost_factor:1,description:"Our state-of-the-art speech to speech model suitable for scenarios where you need maximum control over the content and prosody of your generations.",requires_alpha_access:!1,max_characters_request_free_user:5e3,max_characters_request_subscribed_user:5e3,maximum_text_length_per_request:5e3,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_multilingual_v1",name:"Eleven Multilingual v1",can_be_finetuned:!1,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our first Multilingual model, capability of generating speech in 10 languages. Now outclassed by Multilingual v2 (for content creation) and Turbo v2.5 (for low latency use cases).",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"},{language_id:"de",name:"German"},{language_id:"pl",name:"Polish"},{language_id:"es",name:"Spanish"},{language_id:"it",name:"Italian"},{language_id:"fr",name:"French"},{language_id:"pt",name:"Portuguese"},{language_id:"hi",name:"Hindi"},{language_id:"ar",name:"Arabic"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_multilingual_sts_v2",name:"Eleven Multilingual v2",can_be_finetuned:!0,can_do_text_to_speech:!1,can_do_voice_conversion:!0,can_use_style:!0,can_use_speaker_boost:!0,serves_pro_voices:!1,token_cost_factor:1,description:"Our cutting-edge, multilingual speech-to-speech model is designed for situations that demand unparalleled control over both the content and the prosody of the generated speech across various languages.",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"},{language_id:"ja",name:"Japanese"},{language_id:"zh",name:"Chinese"},{language_id:"de",name:"German"},{language_id:"hi",name:"Hindi"},{language_id:"fr",name:"French"},{language_id:"ko",name:"Korean"},{language_id:"pt",name:"Portuguese"},{language_id:"it",name:"Italian"},{language_id:"es",name:"Spanish"},{language_id:"ru",name:"Russian"},{language_id:"id",name:"Indonesian"},{language_id:"nl",name:"Dutch"},{language_id:"tr",name:"Turkish"},{language_id:"fil",name:"Filipino"},{language_id:"pl",name:"Polish"},{language_id:"sv",name:"Swedish"},{language_id:"bg",name:"Bulgarian"},{language_id:"ro",name:"Romanian"},{language_id:"ar",name:"Arabic"},{language_id:"cs",name:"Czech"},{language_id:"el",name:"Greek"},{language_id:"fi",name:"Finnish"},{language_id:"hr",name:"Croatian"},{language_id:"ms",name:"Malay"},{language_id:"sk",name:"Slovak"},{language_id:"da",name:"Danish"},{language_id:"ta",name:"Tamil"},{language_id:"uk",name:"Ukrainian"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"},{model_id:"eleven_monolingual_v1",name:"Eleven English v1",can_be_finetuned:!1,can_do_text_to_speech:!0,can_do_voice_conversion:!1,can_use_style:!1,can_use_speaker_boost:!1,serves_pro_voices:!1,token_cost_factor:1,description:"Our first ever text to speech model. Now outclassed by Multilingual v2 (for content creation) and Turbo v2.5 (for low latency use cases).",requires_alpha_access:!1,max_characters_request_free_user:1e4,max_characters_request_subscribed_user:1e4,maximum_text_length_per_request:1e4,languages:[{language_id:"en",name:"English"}],model_rates:{character_cost_multiplier:1},concurrency_group:"standard"}],Ae=ce("providers",()=>{const e=de("settings/credentials/providers",{}),{t:r}=ue();async function n(a){try{const i=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${a.apiKey.trim()}`,"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch OpenRouter models: ${i.statusText}`);return(await i.json()).data.map(s=>({id:s.id,name:s.name||s.id,provider:"openrouter-ai",description:s.description||"",contextLength:s.context_length,deprecated:!1}))}catch(i){throw console.error("Error fetching OpenRouter models:",i),i}}const o={"openrouter-ai":{id:"openrouter-ai",nameKey:"settings.pages.providers.provider.openrouter.title",name:"OpenRouter",descriptionKey:"settings.pages.providers.provider.openrouter.description",description:"openrouter.ai",icon:"i-lobe-icons:openrouter",defaultOptions:{baseUrl:"https://openrouter.ai/api/v1/"},createProvider:a=>be(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>n(a)}},openai:{id:"openai",nameKey:"settings.pages.providers.provider.openai.title",name:"OpenAI",descriptionKey:"settings.pages.providers.provider.openai.description",description:"openai.com",icon:"i-lobe-icons:openai",defaultOptions:{baseUrl:"https://api.openai.com/v1/"},createProvider:a=>J(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...J(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"openai",description:"",contextLength:0,deprecated:!1}))}},ollama:{id:"ollama",nameKey:"settings.pages.providers.provider.ollama.title",name:"Ollama",descriptionKey:"settings.pages.providers.provider.ollama.description",description:"ollama.com",icon:"i-lobe-icons:ollama",defaultOptions:{baseUrl:"http://localhost:11434/api/"},createProvider:a=>$(a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...$(a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"ollama",description:"",contextLength:0,deprecated:!1}))}},vllm:{id:"vllm",nameKey:"settings.pages.providers.provider.vllm.title",name:"vLLM",descriptionKey:"settings.pages.providers.provider.vllm.description",description:"vllm.ai",iconColor:"i-lobe-icons:vllm-color",createProvider:a=>$(a.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"llama-2-7b",name:"Llama 2 (7B)",provider:"vllm",description:"Meta's Llama 2 7B parameter model",contextLength:4096},{id:"llama-2-13b",name:"Llama 2 (13B)",provider:"vllm",description:"Meta's Llama 2 13B parameter model",contextLength:4096},{id:"llama-2-70b",name:"Llama 2 (70B)",provider:"vllm",description:"Meta's Llama 2 70B parameter model",contextLength:4096},{id:"mistral-7b",name:"Mistral (7B)",provider:"vllm",description:"Mistral AI's 7B parameter model",contextLength:8192},{id:"mixtral-8x7b",name:"Mixtral (8x7B)",provider:"vllm",description:"Mistral AI's Mixtral 8x7B MoE model",contextLength:32768},{id:"custom",name:"Custom Model",provider:"vllm",description:"Specify a custom model name",contextLength:0}]}},"perplexity-ai":{id:"perplexity-ai",nameKey:"settings.pages.providers.provider.perplexity.title",name:"Perplexity",descriptionKey:"settings.pages.providers.provider.perplexity.description",description:"perplexity.ai",icon:"i-lobe-icons:perplexity",defaultOptions:{baseUrl:"https://api.perplexity.ai"},createProvider:a=>xe(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"sonar-small-online",name:"Sonar Small (Online)",provider:"perplexity-ai",description:"Efficient model with online search capabilities",contextLength:12e3},{id:"sonar-medium-online",name:"Sonar Medium (Online)",provider:"perplexity-ai",description:"Balanced model with online search capabilities",contextLength:12e3},{id:"sonar-large-online",name:"Sonar Large (Online)",provider:"perplexity-ai",description:"Powerful model with online search capabilities",contextLength:12e3},{id:"codey-small",name:"Codey Small",provider:"perplexity-ai",description:"Specialized for code generation and understanding",contextLength:12e3},{id:"codey-large",name:"Codey Large",provider:"perplexity-ai",description:"Advanced code generation and understanding",contextLength:12e3}]}},elevenlabs:{id:"elevenlabs",nameKey:"settings.pages.providers.provider.elevenlabs.title",name:"ElevenLabs",descriptionKey:"settings.pages.providers.provider.elevenlabs.description",description:"elevenlabs.io",icon:"i-simple-icons:elevenlabs",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/",voiceSettings:{similarityBoost:.75,stability:.5}},createProvider:a=>R(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async()=>Oe.map(a=>({id:a.model_id,name:a.name,provider:"elevenlabs",description:a.description,contextLength:0,deprecated:!1})),listVoices:async a=>{const i=R(a.apiKey.trim(),a.baseUrl.trim()),l=await Z({...i.voice()}),s=l.findIndex(b=>b.name.includes("Aria")),g=l.findIndex(b=>b.name.includes("Bill")),I=s!==-1?s:0,F=g!==-1?g:l.length-1,L=Math.min(I,F),z=Math.max(I,F);return[...l.slice(0,L),...l.slice(z+1),...l.slice(L,z+1)].map(b=>({id:b.id,name:b.name,provider:"elevenlabs",previewURL:b.preview_audio_url,languages:b.languages}))}}},xai:{id:"xai",nameKey:"settings.pages.providers.provider.xai.title",name:"xAI",descriptionKey:"settings.pages.providers.provider.xai.description",description:"x.ai",icon:"i-lobe-icons:xai",createProvider:a=>X(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...X(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"xai",description:"",contextLength:0,deprecated:!1}))}},deepseek:{id:"deepseek",nameKey:"settings.pages.providers.provider.deepseek.title",name:"DeepSeek",descriptionKey:"settings.pages.providers.provider.deepseek.description",description:"deepseek.com",iconColor:"i-lobe-icons:deepseek-color",createProvider:a=>D(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...D(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"deepseek",description:"",contextLength:0,deprecated:!1}))}},"together-ai":{id:"together-ai",nameKey:"settings.pages.providers.provider.together.title",name:"Together.ai",descriptionKey:"settings.pages.providers.provider.together.description",description:"together.ai",iconColor:"i-lobe-icons:together-color",createProvider:a=>V(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...V(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"together-ai",description:"",contextLength:0,deprecated:!1}))}},"novita-ai":{id:"novita-ai",nameKey:"settings.pages.providers.provider.novita.title",name:"Novita",descriptionKey:"settings.pages.providers.provider.novita.description",description:"novita.ai",iconColor:"i-lobe-icons:novita-color",createProvider:a=>W(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...W(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"novita-ai",description:"",contextLength:0,deprecated:!1}))}},"fireworks-ai":{id:"fireworks-ai",nameKey:"settings.pages.providers.provider.fireworks.title",name:"Fireworks.ai",descriptionKey:"settings.pages.providers.provider.fireworks.description",description:"fireworks.ai",icon:"i-lobe-icons:fireworks",createProvider:a=>G(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...G(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"fireworks-ai",description:"",contextLength:0,deprecated:!1}))}},"microsoft-speech":{id:"microsoft-speech",nameKey:"settings.pages.providers.provider.microsoft-speech.title",name:"Microsoft / Azure Speech",descriptionKey:"settings.pages.providers.provider.microsoft-speech.description",description:"speech.microsoft.com",iconColor:"i-lobe-icons:microsoft-color",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:a=>Q(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"v1",name:"v1",provider:"microsoft-speech",description:"",contextLength:0,deprecated:!1}],listVoices:async a=>{const i=Q(a.apiKey.trim(),a.baseUrl.trim());return(await Z({...i.voice({region:a.region})})).map(s=>{var g;return{id:s.id,name:s.name,provider:"microsoft-speech",previewURL:s.preview_audio_url,languages:s.languages,gender:(g=s.labels)==null?void 0:g.gender}})}}},"cloudflare-workers-ai":{id:"cloudflare-workers-ai",nameKey:"settings.pages.providers.provider.cloudflare-workers-ai.title",name:"Cloudflare Workers AI",descriptionKey:"settings.pages.providers.provider.cloudflare-workers-ai.description",description:"cloudflare.com",iconColor:"i-lobe-icons:cloudflare-color",createProvider:a=>we(a.apiKey.trim(),a.accountId),capabilities:{listModels:async()=>[]}},"mistral-ai":{id:"mistral-ai",nameKey:"settings.pages.providers.provider.mistral.title",name:"Mistral",descriptionKey:"settings.pages.providers.provider.mistral.description",description:"mistral.ai",iconColor:"i-lobe-icons:mistral-color",createProvider:a=>N(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...N(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"mistral-ai",description:"",contextLength:0,deprecated:!1}))}},"moonshot-ai":{id:"moonshot-ai",nameKey:"settings.pages.providers.provider.moonshot.title",name:"Moonshot AI",descriptionKey:"settings.pages.providers.provider.moonshot.description",description:"moonshot.ai",icon:"i-lobe-icons:moonshot",createProvider:a=>H(a.apiKey.trim(),a.baseUrl.trim()),capabilities:{listModels:async a=>(await f({...H(a.apiKey.trim(),a.baseUrl.trim()).model()})).map(i=>({id:i.id,name:i.id,provider:"moonshot-ai",description:"",contextLength:0,deprecated:!1}))}}};function v(a){const i=e.value[a];if(!i)return!1;switch(a){case"openrouter-ai":return!!i.apiKey&&!!i.baseUrl;case"openai":return!!i.apiKey;case"ollama":return!!i.baseUrl;case"vllm":return!!i.baseUrl;case"elevenlabs":return!!i.apiKey;case"xai":return!!i.apiKey;case"deepseek":return!!i.apiKey;case"together-ai":return!!i.apiKey;case"novita-ai":return!!i.apiKey;case"fireworks-ai":return!!i.apiKey;case"microsoft-speech":return!!i.apiKey&&!!i.region;case"cloudflare-workers-ai":return!!i.apiKey;case"mistral-ai":return!!i.apiKey;case"moonshot-ai":return!!i.apiKey;default:return!1}}const t=O({});function d(a){var i;if(!e.value[a]){const l=o[a];e.value[a]={baseUrl:((i=l.defaultOptions)==null?void 0:i.baseUrl)||""}}}Object.keys(o).forEach(d);function y(){Object.keys(o).forEach(a=>{t.value[a]=v(a)})}y(),pe(e,y,{deep:!0});const m=x(()=>Object.keys(o).filter(a=>t.value[a])),c=O({}),M=O({}),w=O({});async function P(a){const i=e.value[a];if(!i)return[];const l=o[a];if(!l)return[];M.value[a]=!0,w.value[a]=null;try{const s=l.capabilities.listModels?await l.capabilities.listModels(i):[];return c.value[a]=s.map(g=>({id:g.id,name:g.name,description:g.description,contextLength:g.contextLength,deprecated:g.deprecated,provider:a})),c.value[a]}catch(s){return console.error(`Error fetching models for ${a}:`,s),w.value[a]=s instanceof Error?s.message:"Unknown error",[]}finally{M.value[a]=!1}}function S(a){return c.value[a]||[]}const C=x(()=>{const a=[];for(const i of m.value)a.push(...c.value[i]||[]);return a});async function ae(){for(const a of m.value)o[a].capabilities.listModels&&await P(a)}function U(a){const i=o[a];if(!i)throw new Error(`Provider metadata for ${a} not found`);return{...i,localizedName:r(i.nameKey,i.name),localizedDescription:r(i.descriptionKey,i.description)}}const re=x(()=>Object.values(o).map(a=>({...a,localizedName:r(a.nameKey,a.name),localizedDescription:r(a.descriptionKey,a.description),configured:t.value[a.id]||!1})));function E(a){const i=e.value[a];if(!i)throw new Error(`Provider credentials for ${a} not found`);const l=o[a];if(!l)throw new Error(`Provider metadata for ${a} not found`);try{return l.createProvider(i)}catch(s){throw console.error(`Error creating provider instance for ${a}:`,s),s}}const K=x(()=>m.value.map(a=>U(a))),ie=x(()=>K.value.filter(a=>{const i=E(a.id);return"chat"in i&&typeof i.chat=="function"})),ne=x(()=>K.value.filter(a=>{const i=E(a.id);return"transcription"in i&&typeof i.transcription=="function"})),te=x(()=>K.value.filter(a=>{const i=E(a.id);return"speech"in i&&typeof i.speech=="function"}));function se(a){return e.value[a]}return{providers:e,getProviderConfig:se,availableProviders:m,configuredProviders:t,providerMetadata:o,getProviderMetadata:U,allProvidersMetadata:re,initializeProvider:d,validateProvider:v,availableModels:c,isLoadingModels:M,modelLoadError:w,fetchModelsForProvider:P,getModelsForProvider:S,allAvailableModels:C,loadModelsForConfiguredProviders:ae,getProviderInstance:E,availableProvidersMetadata:K,availableTextGenerationsProvidersMetadata:ie,availableAudioSpeechProvidersMetadata:te,availableAudioTranscriptionProvidersMetadata:ne}});export{ge as a,$e as b,Y as c,ve as d,f as l,_e as r,Ae as u}; diff --git a/assets/queue-CdKSGkpu.js b/assets/queue-CHfe46kZ.js similarity index 90% rename from assets/queue-CdKSGkpu.js rename to assets/queue-CHfe46kZ.js index 9f6c685dcee414401641cc6dd7e0e901f7c8370f..f3c10391a8b891bc4015d2cd163ea3964c7ecab5 100644 --- a/assets/queue-CdKSGkpu.js +++ b/assets/queue-CHfe46kZ.js @@ -1 +1 @@ -import{u as o}from"./queue-EbaGahVd.js";import{d as v,g as h,m as g,c as k,o as w,a as I}from"./index-rD0Uu1v9.js";const Q=v({__name:"queue",setup(P){function i(e){return new Promise(a=>setTimeout(a,e))}const n=h(""),d=o({handlers:[async e=>{console.log("ready to play speech audio for",e)}]}),u=o({handlers:[async e=>{console.log("ready to stream speech audio for",e),d.add(e.data)}]}),c=o({handlers:[async e=>{const a=[".","?","!"];let s=!1;for(const t of a){if(!e.data.includes(t))continue;const r=e.data.indexOf(t),p=e.data.slice(0,r+1),y=e.data.slice(r+1);n.value+=p,u.add(n.value.trim()),n.value=y,s=!0}s||(n.value+=e.data)}]}),l=["Hello"," N","eko","! I"," am"," an"," AI"," assistant"," trained"," to"," help"," with"," a"," variety"," of"," tasks"," such"," as"," answering"," questions",","," providing"," information",","," giving"," recommendations",","," and"," more",". How"," can"," I"," assist"," you"," today","?","Hello"," N","eko",","," I"," am"," an"," AI"," assistant","."," I"," can"," help"," answer"," questions",","," provide"," information",","," assist"," with"," tasks",","," and"," engage"," in"," conversation","."," How"," can"," I"," assist"," you"," today","?"];async function f(){for(const e of l)await i(100),c.add(e)}async function m(){f()}return g(()=>{m()}),(e,a)=>(w(),k("div",null,a[0]||(a[0]=[I("div",null,null,-1)])))}});export{Q as default}; +import{u as o}from"./queue-DW8o1RLT.js";import{d as v,g as h,m as g,c as k,o as w,a as I}from"./index-Dlp4W1Zl.js";const Q=v({__name:"queue",setup(P){function i(e){return new Promise(a=>setTimeout(a,e))}const n=h(""),d=o({handlers:[async e=>{console.log("ready to play speech audio for",e)}]}),u=o({handlers:[async e=>{console.log("ready to stream speech audio for",e),d.add(e.data)}]}),c=o({handlers:[async e=>{const a=[".","?","!"];let s=!1;for(const t of a){if(!e.data.includes(t))continue;const r=e.data.indexOf(t),p=e.data.slice(0,r+1),y=e.data.slice(r+1);n.value+=p,u.add(n.value.trim()),n.value=y,s=!0}s||(n.value+=e.data)}]}),l=["Hello"," N","eko","! I"," am"," an"," AI"," assistant"," trained"," to"," help"," with"," a"," variety"," of"," tasks"," such"," as"," answering"," questions",","," providing"," information",","," giving"," recommendations",","," and"," more",". How"," can"," I"," assist"," you"," today","?","Hello"," N","eko",","," I"," am"," an"," AI"," assistant","."," I"," can"," help"," answer"," questions",","," provide"," information",","," assist"," with"," tasks",","," and"," engage"," in"," conversation","."," How"," can"," I"," assist"," you"," today","?"];async function f(){for(const e of l)await i(100),c.add(e)}async function m(){f()}return g(()=>{m()}),(e,a)=>(w(),k("div",null,a[0]||(a[0]=[I("div",null,null,-1)])))}});export{Q as default}; diff --git a/assets/queue-EbaGahVd.js b/assets/queue-DW8o1RLT.js similarity index 91% rename from assets/queue-EbaGahVd.js rename to assets/queue-DW8o1RLT.js index a81729c6a8c71562447fc8d9c28218f7385136f2..aaa5549b855dc822d023a2aa30b22ca313385954 100644 --- a/assets/queue-EbaGahVd.js +++ b/assets/queue-DW8o1RLT.js @@ -1 +1 @@ -import{g as l}from"./index-rD0Uu1v9.js";function m(f){const t=l([]),a=l(!1),d={add:[],pick:[],processing:[],error:[],processed:[],done:[]},s={};function c(n,e){d[n].push(e)}function r(n,...e){d[n].forEach(i=>{i(...e)})}function h(n,e){s[n]=s[n]||[],s[n].push(e)}function p(n,...e){(s[n]||[]).forEach(i=>{i(...e)})}async function v(n){t.value.push(n),r("add",n)}function g(){const n=t.value.shift();if(n)return r("pick",n),n}async function u(){if(a.value)return;const n=g();if(n){a.value=!0;for(const e of f.handlers){r("processing",n,e);try{const o=await e({data:n,itemsToBeProcessed:()=>t.value.length,emit:p});r("processed",n,o,e)}catch(o){r("error",n,o,e);continue}}a.value=!1,r("done",n),t.value.length>0&&u()}}return c("add",u),c("done",u),{add:v,on:c,onHandlerEvent:h,queue:t}}export{m as u}; +import{g as l}from"./index-Dlp4W1Zl.js";function m(f){const t=l([]),a=l(!1),d={add:[],pick:[],processing:[],error:[],processed:[],done:[]},s={};function c(n,e){d[n].push(e)}function r(n,...e){d[n].forEach(i=>{i(...e)})}function h(n,e){s[n]=s[n]||[],s[n].push(e)}function p(n,...e){(s[n]||[]).forEach(i=>{i(...e)})}async function v(n){t.value.push(n),r("add",n)}function g(){const n=t.value.shift();if(n)return r("pick",n),n}async function u(){if(a.value)return;const n=g();if(n){a.value=!0;for(const e of f.handlers){r("processing",n,e);try{const o=await e({data:n,itemsToBeProcessed:()=>t.value.length,emit:p});r("processed",n,o,e)}catch(o){r("error",n,o,e);continue}}a.value=!1,r("done",n),t.value.length>0&&u()}}return c("add",u),c("done",u),{add:v,on:c,onHandlerEvent:h,queue:t}}export{m as u}; diff --git a/assets/queues-kGVt0l-U.js b/assets/queues-CJq1hDiQ.js similarity index 89% rename from assets/queues-kGVt0l-U.js rename to assets/queues-CJq1hDiQ.js index 33ae907edf4e38e3f285c258dce3572312f19645..8b1a7ca37a2f7468c10a5e85a590ad108feb06d3 100644 --- a/assets/queues-kGVt0l-U.js +++ b/assets/queues-CJq1hDiQ.js @@ -1 +1 @@ -import{d as m,bF as p,bG as v,g as u,w as y,A as k,bJ as w,o as b,c as h,n as E}from"./index-rD0Uu1v9.js";import{E as f}from"./live2d-zip-loader-BdiFCiUD.js";import{u as l}from"./queue-EbaGahVd.js";const D=m({__name:"BasicTextarea",props:{modelValue:{default:""},modelModifiers:{}},emits:p(["submit"],["update:modelValue"]),setup(o,{emit:n}){const e=n,t=v(o,"modelValue"),a=u(),s=u("auto");function i(r){r.code==="Enter"&&!r.shiftKey&&(r.preventDefault(),e("submit",t.value))}return y(t,()=>{s.value="auto",requestAnimationFrame(()=>{a.value&&(s.value=`${a.value.scrollHeight}px`)})},{immediate:!0}),(r,d)=>k((b(),h("textarea",{ref_key:"textareaRef",ref:a,"onUpdate:modelValue":d[0]||(d[0]=c=>t.value=c),style:E({height:s.value}),onKeydown:i},null,36)),[[w,t.value]])}}),M="<|llm_inference_end|>";function A(o){function n(e){for(const t of f)if(e.includes(t))return{ok:!0,emotion:t};return{ok:!1,emotion:""}}return l({handlers:[async e=>{if(f.includes(e.data)){e.emit("emotion",e.data),await o.add(e.data);return}{const{ok:t,emotion:a}=n(e.data);t&&(e.emit("emotion",a),await o.add(a))}}]})}function N(){function o(e){if(!/<\|DELAY:\d+\|>/i.test(e))return{ok:!1,delay:0};const t=/<\|DELAY:(\d+)\|>/i.exec(e),a=t==null?void 0:t[1];if(!a)return{ok:!1,delay:0};const s=Number.parseFloat(a);return s<=0||Number.isNaN(s)?{ok:!0,delay:0}:{ok:!0,delay:s}}function n(e){return new Promise(t=>setTimeout(t,e))}return l({handlers:[async e=>{const{ok:t,delay:a}=o(e.data);t&&(e.emit("delay",a),await n(a*1e3))}]})}function T(o){const n=u("");return l({handlers:[async e=>{if(e.data===M){const a=n.value.trim();a&&await o.add(a),n.value="";return}const t=/[.?!]/;for(n.value+=e.data;n.value;){const a=t.exec(n.value);if(!a||typeof a.index>"u")break;const s=n.value.slice(0,a.index+1),i=n.value.slice(a.index+1);await o.add(s),n.value=i}}]})}export{D as _,A as a,N as b,M as l,T as u}; +import{d as m,bF as p,bG as v,g as u,w as y,A as k,bJ as w,o as b,c as h,n as E}from"./index-Dlp4W1Zl.js";import{E as f}from"./live2d-zip-loader-C5j9stxV.js";import{u as l}from"./queue-DW8o1RLT.js";const D=m({__name:"BasicTextarea",props:{modelValue:{default:""},modelModifiers:{}},emits:p(["submit"],["update:modelValue"]),setup(o,{emit:n}){const e=n,t=v(o,"modelValue"),a=u(),s=u("auto");function i(r){r.code==="Enter"&&!r.shiftKey&&(r.preventDefault(),e("submit",t.value))}return y(t,()=>{s.value="auto",requestAnimationFrame(()=>{a.value&&(s.value=`${a.value.scrollHeight}px`)})},{immediate:!0}),(r,d)=>k((b(),h("textarea",{ref_key:"textareaRef",ref:a,"onUpdate:modelValue":d[0]||(d[0]=c=>t.value=c),style:E({height:s.value}),onKeydown:i},null,36)),[[w,t.value]])}}),M="<|llm_inference_end|>";function A(o){function n(e){for(const t of f)if(e.includes(t))return{ok:!0,emotion:t};return{ok:!1,emotion:""}}return l({handlers:[async e=>{if(f.includes(e.data)){e.emit("emotion",e.data),await o.add(e.data);return}{const{ok:t,emotion:a}=n(e.data);t&&(e.emit("emotion",a),await o.add(a))}}]})}function N(){function o(e){if(!/<\|DELAY:\d+\|>/i.test(e))return{ok:!1,delay:0};const t=/<\|DELAY:(\d+)\|>/i.exec(e),a=t==null?void 0:t[1];if(!a)return{ok:!1,delay:0};const s=Number.parseFloat(a);return s<=0||Number.isNaN(s)?{ok:!0,delay:0}:{ok:!0,delay:s}}function n(e){return new Promise(t=>setTimeout(t,e))}return l({handlers:[async e=>{const{ok:t,delay:a}=o(e.data);t&&(e.emit("delay",a),await n(a*1e3))}]})}function T(o){const n=u("");return l({handlers:[async e=>{if(e.data===M){const a=n.value.trim();a&&await o.add(a),n.value="";return}const t=/[.?!]/;for(n.value+=e.data;n.value;){const a=t.exec(n.value);if(!a||typeof a.index>"u")break;const s=n.value.slice(0,a.index+1),i=n.value.slice(a.index+1);await o.add(s),n.value=i}}]})}export{D as _,A as a,N as b,M as l,T as u}; diff --git a/assets/speech-BAXAx1sa.js b/assets/speech-BzDSuaZq.js similarity index 98% rename from assets/speech-BAXAx1sa.js rename to assets/speech-BzDSuaZq.js index 3a05811896a88d19dc6ffb315acb3b0f4462fbbc..b350a75090a0000a783dbe16104e2d3f3782fd28 100644 --- a/assets/speech-BAXAx1sa.js +++ b/assets/speech-BzDSuaZq.js @@ -1 +1 @@ -import{d as O,g as V,m as ne,w as Z,p as ie,c as i,o as n,bx as H,by as Y,a as e,n as me,z as C,bF as K,bG as J,A as j,bA as pe,C as $,D as k,b as S,y as N,bn as ee,h as fe,cc as ge,bJ as W,x as X,i as xe,s as le,bE as be,H as he,bw as ye,e as t,bo as ke,ad as I,bI as we}from"./index-rD0Uu1v9.js";import{_ as oe,a as ae,b as _e}from"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DtA_pyWZ.js";import{_ as Se}from"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import{R as Ve,a as Me}from"./RadioCardDetailManySelect-cGsz75Pf.js";import{_ as Ce}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import{_ as $e}from"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";import"./live2d-zip-loader-BdiFCiUD.js";import{u as Pe}from"./providers-Dg3FpvfZ.js";import{u as Ue,g as Le}from"./speech-CUKri9wm.js";import{b as re}from"./route-block-B_A1xBdJ.js";const qe=O({__name:"AudioSpectrum",props:{stream:null,bars:{default:32},minFreq:{default:60},maxFreq:{default:4e3}},setup(o){const l=o,x=V(Array.from({length:l.bars}).fill(0));ne(()=>{p()}),Z(()=>l.stream,()=>{p()});function p(){if(!l.stream)return;const c=new(window.AudioContext||window.webkitAudioContext),g=c.createMediaStreamSource(l.stream),v=c.createAnalyser();v.fftSize=2048,g.connect(v);const b=v.frequencyBinCount,M=new Uint8Array(b),f=c.sampleRate/v.fftSize,w=Math.floor(l.minFreq/f),P=Math.floor(l.maxFreq/f),L=P-w,A=Math.floor(L/l.bars),E=()=>{try{requestAnimationFrame(E),v.getByteFrequencyData(M);const q=Array.from({length:l.bars}).fill(0);for(let T=0;Tie(c.$slots,"default",{frequencies:x.value})}}),Ae={"h-full":"",flex:"","items-center":"","gap-1":""},Re=5,Ee=O({__name:"AudioSpectrumVisualizer",props:{frequencies:null,barsClass:null},setup(o){const l=o;function x(c,g){return .1+(1-.1)*(c/g)}function p(c,g){const v=x(g,l.frequencies.length);return Math.min(100,Math.max(10,c*100*Re*v))}return(c,g)=>(n(),i("div",Ae,[(n(!0),i(H,null,Y(o.frequencies,(v,b)=>(n(),i("div",{key:b,"h-full":"",flex:"","flex-1":"","items-end":""},[e("div",{transition:"all 100 ease-in-out","mx-auto":"","my-0":"","w-full":"","rounded-full":"",class:C(o.barsClass),style:me({height:`${p(v,b)}%`})},null,6)]))),128))]))}}),Te={class:"p-3"},ze={class:"flex items-start"},Be=["checked","name","value"],Fe={class:"relative mr-3 mt-0.5 flex-shrink-0"},Ie={key:0,class:"i-solar:pause-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},Ne={key:1,class:"i-solar:play-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},De={key:1,class:"mt-auto w-full flex items-center justify-center bg-neutral-50 py-3 text-xs text-neutral-400 italic dark:bg-neutral-800/50 dark:text-neutral-600"},je={class:"flex-1 cursor-pointer"},Oe={class:"flex items-center"},Qe={key:0,class:"mt-1 flex flex-wrap gap-1"},He={key:1,class:"mt-3"},Ge={relative:""},Je={key:0,class:"h-16 px-3 pb-2"},Ye=O({__name:"VoiceCard",props:K({name:null,voice:null,currentlyPlayingId:null,customInputPlaceholder:{default:"Enter custom voice name"},showVisualizer:{type:Boolean,default:!0},audioStream:{default:null}},{"voice-id":{required:!1,default:""},"voice-idModifiers":{},"custom-voice-name":{required:!1,default:""},"custom-voice-nameModifiers":{}}),emits:K(["togglePlayback"],["update:voice-id","update:custom-voice-name"]),setup(o,{emit:l}){const x=o,p=l,c=J(o,"voice-id"),g=J(o,"custom-voice-name");function v(h){return h.previewURL||h.preview_audio_url}function b(h){var w,P,L;const f=[];if((w=h.labels)!=null&&w.gender&&f.push(h.labels.gender),(P=h.labels)!=null&&P.age&&f.push(h.labels.age),(L=h.labels)!=null&&L.accent&&f.push(h.labels.accent),h.languages&&h.languages.length>0){const A=h.languages.map(E=>E.name).join(", ");f.push(A)}return f}function M(){p("togglePlayback",x.voice)}return(h,f)=>(n(),i("label",{border:"2px solid",class:C(["scroll-snap-align-start form_voice-card relative flex flex-col overflow-hidden rounded-xl",[c.value===x.voice.id?"bg-primary-50 dark:bg-primary-900/20 border-primary-100 dark:border-primary-900 hover:border-primary-500/30 dark:hover:border-primary-400/30":"bg-white dark:bg-neutral-900/20 border-neutral-100 dark:border-neutral-900 hover:border-primary-500/30 dark:hover:border-primary-400/30",c.value===x.voice.id?"form_voice-card-active":""]]),transition:"all duration-200 ease-in-out"},[e("div",Te,[e("div",ze,[j(e("input",{"onUpdate:modelValue":f[0]||(f[0]=w=>c.value=w),checked:c.value===x.voice.id,type:"radio",name:o.name,value:x.voice.id,class:"absolute cursor-pointer opacity-0"},null,8,Be),[[pe,c.value]]),e("div",Fe,[e("div",{class:C(["size-5 border-2 rounded-full transition-colors duration-200",[c.value===x.voice.id?"border-primary-500 dark:border-primary-400":"border-neutral-300 dark:border-neutral-600"]])},[e("div",{class:C(["absolute left-1/2 top-1/2 size-3 rounded-full transition-opacity duration-200 -translate-x-1/2 -translate-y-1/2",[c.value===x.voice.id?"opacity-100 bg-primary-500 dark:bg-primary-400":"opacity-0"]])},null,2)],2)]),v(o.voice)?(n(),i("button",{key:0,absolute:"","right-0":"",top:"0","z-100":"",class:C(["translate-x-[-50%] translate-y-[50%]",[o.currentlyPlayingId===o.voice.id?"text-white dark:text-white":""]]),onClick:M},[o.currentlyPlayingId===o.voice.id?(n(),i("div",Ie)):(n(),i("div",Ne))],2)):(n(),i("div",De," No preview available ")),e("div",je,[e("div",Oe,[e("span",{class:C(["line-clamp-1 font-medium",[c.value===o.voice.id?"text-neutral-700 dark:text-neutral-300":"text-neutral-700 dark:text-neutral-400"]])},k(o.voice.name),3)]),b(o.voice).length>0?(n(),i("div",Qe,[(n(!0),i(H,null,Y(b(o.voice),(w,P)=>(n(),i("span",{key:P,class:C(["inline-flex items-center rounded-md px-1.5 py-0.5 text-xs",[c.value===o.voice.id?"bg-primary-100 text-primary-700 dark:bg-primary-900/30 dark:text-primary-400":"bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300"]])},k(w),3))),128))])):$("",!0),o.voice.customizable&&c.value===o.voice.id?(n(),i("div",He,[S($e,{modelValue:g.value,"onUpdate:modelValue":f[1]||(f[1]=w=>g.value=w),type:"text",class:"w-full border border-neutral-300 rounded bg-white px-2 py-1 text-sm dark:border-neutral-700 dark:bg-neutral-900",placeholder:o.customInputPlaceholder},null,8,["modelValue","placeholder"])])):$("",!0),o.voice.description?(n(),i("div",{key:2,class:C(["line-clamp-2 mt-1 text-xs",[c.value===o.voice.id?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]])},k(o.voice.description),3)):$("",!0)])])]),e("div",Ge,[S(Ce,null,{default:N(()=>[o.showVisualizer&&o.currentlyPlayingId===o.voice.id&&o.audioStream?(n(),i("div",Je,[S(qe,{stream:o.audioStream,bars:24,"min-freq":60,"max-freq":4e3},{default:N(({frequencies:w})=>[S(Ee,{frequencies:w,"bars-class":c.value===o.voice.id?"bg-primary-500 dark:bg-primary-400":"bg-neutral-400 dark:bg-neutral-600"},null,8,["frequencies","bars-class"])]),_:1},8,["stream"])])):$("",!0)]),_:1})])],2))}}),Ke=ee(Ye,[["__scopeId","data-v-dbab964e"]]),We={class:"voice-preview-player"},Xe={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},Ze=["placeholder"],et={class:"mt-4 space-y-2"},tt={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},st={key:1,class:"flex items-center gap-3 border border-2 border-amber-200 rounded-xl bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},lt={class:"flex flex-col"},ot={class:"font-medium"},at={class:"text-sm text-amber-600 dark:text-amber-400"},rt={class:"relative"},nt=O({__name:"VoiceCardManySelect",props:K({voices:null,searchable:{type:Boolean,default:!0},searchPlaceholder:{default:"Search voices..."},searchNoResultsTitle:{default:"No voices found"},searchNoResultsDescription:{default:"Try a different search term"},searchResultsText:{default:"{count} of {total} voices"},customInputPlaceholder:{default:"Enter custom voice name"},expandButtonText:{default:"Show more"},collapseButtonText:{default:"Show less"},playButtonText:{default:"Play sample"},pauseButtonText:{default:"Pause"},showVisualizer:{type:Boolean,default:!0}},{"search-query":{required:!1,default:""},"search-queryModifiers":{},"voice-id":{required:!1,default:""},"voice-idModifiers":{}}),emits:["update:search-query","update:voice-id"],setup(o){const l=o,x=V(!1),p=V(),c=V(new Map),g=V(new Map),v=V(new Map),b=V(new Map),M=V(null);function h(){return M.value||(M.value=new(window.AudioContext||window.webkitAudioContext)),M.value}const f=J(o,"search-query"),w=J(o,"voice-id"),P=fe(()=>{if(!f.value)return l.voices;const a=f.value.toLowerCase();return l.voices.filter(r=>{const d=r.name.toLowerCase().includes(a),m=r.description&&r.description.toLowerCase().includes(a),_=r.tags&&r.tags.some(y=>y.toLowerCase().includes(a)),U=r.labels&&Object.values(r.labels).some(y=>typeof y=="string"&&y.toLowerCase().includes(a)),B=r.languages&&r.languages.some(y=>y.name.toLowerCase().includes(a)||y.code.toLowerCase().includes(a));return d||m||_||U||B})});function L(a){return a.previewURL||a.preview_audio_url}function A(a){const r=L(a);if(!r)return null;if(c.value.has(a.id))return c.value.get(a.id)||null;const d=new Audio(r);return d.crossOrigin="anonymous",d.preload="auto",d.addEventListener("ended",()=>{if(p.value===a.id){p.value=void 0;const m=g.value.get(a.id);m&&(m.getTracks().forEach(_=>_.stop()),g.value.delete(a.id))}}),c.value.set(a.id,d),d}function E(a,r){try{if(g.value.has(r))return g.value.get(r)||null;const d=h();if(b.value.has(r)){const B=b.value.get(r),y=d.createMediaStreamDestination();B.connect(y);const F=y.stream;return g.value.set(r,F),F}const m=d.createMediaElementSource(a);b.value.set(r,m),m.connect(d.destination);const _=d.createMediaStreamDestination();m.connect(_);const U=_.stream;return g.value.set(r,U),U}catch(d){return console.error("Failed to create audio stream for visualizer:",d),null}}function q(a){try{if(!L(a))return;const d=A(a);if(!d)return;if(p.value===a.id){d.pause(),p.value=void 0;const m=g.value.get(a.id);m&&(m.getTracks().forEach(_=>_.stop()),g.value.delete(a.id));return}if(p.value){const m=c.value.get(p.value);m&&m.pause();const _=g.value.get(p.value);_&&(_.getTracks().forEach(U=>U.stop()),g.value.delete(p.value))}l.showVisualizer&&!g.value.has(a.id)&&E(d,a.id),d.currentTime=0,d.play().catch(m=>{console.error("Failed to play audio:",m)}),p.value=a.id}catch(r){console.error(r),p.value=void 0}}function T(){c.value.forEach(a=>{a.pause(),a.src=""}),c.value.clear(),g.value.forEach(a=>{a.getTracks().forEach(r=>r.stop())}),g.value.clear(),v.value.forEach(a=>{a.state!=="closed"&&a.close()}),v.value.clear(),b.value.clear(),p.value=void 0}Z(f,()=>{if(p.value){const a=c.value.get(p.value);a&&a.pause();const r=g.value.get(p.value);r&&(r.getTracks().forEach(d=>d.stop()),g.value.delete(p.value)),p.value=void 0}}),ge(T);const z=V("");return(a,r)=>(n(),i("div",We,[o.searchable?(n(),i("div",Xe,[r[4]||(r[4]=e("div",{class:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"},[e("div",{"i-solar:magnifer-line-duotone":"",class:"text-neutral-500 dark:text-neutral-400"})],-1)),j(e("input",{"onUpdate:modelValue":r[0]||(r[0]=d=>f.value=d),type:"search",class:"w-full rounded-xl p-2.5 pl-10 text-sm outline-none",border:"focus:primary-100 dark:focus:primary-400/50 2 solid neutral-200 dark:neutral-800",transition:"all duration-200 ease-in-out",bg:"white dark:neutral-900",placeholder:o.searchPlaceholder},null,8,Ze),[[W,f.value]])])):$("",!0),e("div",et,[f.value?(n(),i("div",tt,k(o.searchResultsText.replace("{count}",P.value.length.toString()).replace("{total}",o.voices.length.toString())),1)):$("",!0),f.value&&P.value.length===0?(n(),i("div",st,[r[5]||(r[5]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",lt,[e("span",ot,k(o.searchNoResultsTitle),1),e("span",at,k(o.searchNoResultsDescription.replace("{query}",f.value)),1)])])):$("",!0),e("div",rt,[e("div",{class:C(["scrollbar-hide grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto",[x.value?"grid-cols-1 md:grid-cols-2 grid-flow-row auto-cols-auto":""]]),transition:"all duration-200 ease-in-out",style:{"scroll-snap-type":"x mandatory"}},[(n(!0),i(H,null,Y(P.value,d=>(n(),X(Ke,{key:d.id,"voice-id":w.value,"onUpdate:voiceId":r[1]||(r[1]=m=>w.value=m),"custom-voice-name":z.value,"onUpdate:customVoiceName":r[2]||(r[2]=m=>z.value=m),name:"voice",voice:d,"currently-playing-id":p.value,"custom-input-placeholder":o.customInputPlaceholder,"show-visualizer":o.showVisualizer,"audio-stream":g.value.get(d.id),onTogglePlayback:q},null,8,["voice-id","custom-voice-name","voice","currently-playing-id","custom-input-placeholder","show-visualizer","audio-stream"]))),128))],2),e("div",{bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"",class:C([x.value?"w-full":"mt-4 w-full rounded-lg"])},[e("button",{"w-full":"",flex:"","items-center":"","justify-center":"","gap-2":"","rounded-lg":"","py-2":"",transition:"all duration-200 ease-in-out",class:C([x.value?"bg-primary-500 hover:bg-primary-600 text-white":"bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800"]),onClick:r[3]||(r[3]=d=>x.value=!x.value)},[e("span",null,k(x.value?o.collapseButtonText:o.expandButtonText),1),e("div",{class:C([x.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),it=ee(nt,[["__scopeId","data-v-070104a7"]]),ut=O({__name:"Skeleton",props:{animation:{default:"pulse"}},setup(o){const l=o;return(x,p)=>(n(),i("div",{class:C(["skeleton",l.animation!=="none"?`skeleton-${l.animation}`:""]),bg:"neutral-200 dark:neutral-800",overflow:"hidden"},[ie(x.$slots,"default",{},void 0,!0)],2))}}),Q=ee(ut,[["__scopeId","data-v-f404da2a"]]),dt={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},ct={relative:""},vt={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},mt={text:"neutral-300 dark:neutral-500","text-nowrap":""},pt={"text-nowrap":"","text-3xl":"","font-semibold":""},ft={flex:"~ col md:row gap-6"},gt={bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4",class:"w-full md:w-[40%]"},xt={flex:"~ col gap-4"},bt={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},ht={text:"neutral-400 dark:neutral-500"},yt={"max-w-full":""},kt={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},wt={key:1},_t={key:0},St={flex:"~ col gap-4"},Vt={class:"text-lg md:text-2xl"},Mt={text:"neutral-400 dark:neutral-400"},Ct={key:0,class:"flex items-center justify-center py-4"},$t={key:1,class:"flex items-center gap-3 border border-red-200 rounded-lg bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20"},Pt={class:"flex flex-col"},Ut={class:"font-medium"},Lt={class:"text-sm text-red-600 dark:text-red-400"},qt={key:2,class:"flex items-center gap-3 border border-amber-200 rounded-lg bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},At={class:"flex flex-col"},Rt={class:"font-medium"},Et={class:"text-sm text-amber-600 dark:text-amber-400"},Tt={key:0},zt={flex:"~ col gap-4"},Bt={key:0},Ft={class:"flex flex-col gap-4"},It={flex:"~ row gap-4"},Nt={key:1,class:"space-y-6"},Dt={key:2,class:"flex items-center gap-3 border border-2 border-red-200 rounded-lg bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20"},jt={class:"flex flex-col"},Ot={class:"text-sm text-red-600 dark:text-red-400"},Qt={key:3,class:"flex items-center gap-3 border border-2 border-amber-200 rounded-lg bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},Ht={flex:"~ col gap-4"},Gt={key:4,class:"mt-2 space-y-6"},Jt={key:0},Yt={flex:"~ col gap-4"},Kt={flex:"~ col gap-6",class:"w-full md:w-[60%]"},Wt={"w-full":"","rounded-xl":""},Xt={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},Zt={class:"inline-flex items-center gap-4"},es={flex:"~ col gap-4"},ts=["placeholder"],ss={flex:"~ row","gap-4":""},ls=["disabled"],os={flex:"~ row","items-center":"","gap-2":""},as=["src"],rs=O({__name:"speech",setup(o){const{t:l}=xe(),x=Pe(),p=Ue(),{availableProviders:c,availableAudioSpeechProvidersMetadata:g}=le(x),{activeSpeechProvider:v,activeSpeechModel:b,activeSpeechVoice:M,activeSpeechVoiceId:h,pitch:f,isLoadingSpeechProviderVoices:w,supportsModelListing:P,providerModels:L,isLoadingActiveProviderModels:A,activeProviderModelError:E,modelSearchQuery:q,speechProviderError:T,ssmlEnabled:z,availableVoices:a}=le(p),r=be(),d=V(""),m=V(!1),_=V("Hello, my name is AI Assistant"),U=V(""),B=V(!1),y=V(""),F=V(null),te=V("");ne(async()=>{await p.loadVoicesForProvider(v.value),await x.loadModelsForConfiguredProviders()}),Z(v,async()=>{await p.loadVoicesForProvider(v.value),await x.loadModelsForConfiguredProviders()});async function ue(){if(!_.value.trim()&&!m.value||m.value&&!U.value.trim())return;if(!b.value){console.error("No model selected");return}if(!M.value){console.error("No voice selected");return}const R=x.getProviderInstance(v.value);if(!R){console.error("Failed to initialize speech provider");return}const s=x.getProviderConfig(v.value);B.value=!0,te.value="";try{y.value&&se();const D=m.value?U.value:p.generateSSML(_.value,M.value,{...s,pitch:f.value}),G=await Le({...R.speech(b.value,s),input:D,voice:M.value.id});y.value=URL.createObjectURL(new Blob([G])),setTimeout(()=>{F.value&&F.value.play()},100)}catch(D){console.error("Error generating speech:",D),te.value=D instanceof Error?D.message:"An unknown error occurred"}finally{B.value=!1}}function se(){F.value&&(F.value.pause(),F.value.currentTime=0),y.value&&(URL.revokeObjectURL(y.value),y.value="")}he(()=>{y.value&&URL.revokeObjectURL(y.value)});function de(R){M.value={id:R,name:R,description:R,previewURL:R,languages:[{code:"en",title:"English"}],provider:v.value,gender:"male"}}function ce(R){b.value=R}return(R,s)=>{var G;const D=ye("motion");return n(),i(H,null,[j((n(),i("div",dt,[e("button",{onClick:s[0]||(s[0]=u=>t(r).back())},s[14]||(s[14]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-xl":""},null,-1)])),e("h1",ct,[e("div",vt,[e("span",mt,k(t(l)("settings.pages.modules.title")),1)]),e("div",pt,k(t(l)("settings.pages.modules.speech.title")),1)])])),[[D]]),e("div",ft,[e("div",gt,[e("div",null,[e("div",xt,[e("div",null,[e("h2",bt,k(t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.title")),1),e("div",ht,[e("span",null,k(t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.description")),1)])]),e("div",yt,[t(c).length>0?(n(),i("fieldset",kt,[(n(!0),i(H,null,Y(t(g),u=>(n(),X(t(Me),{id:u.id,key:u.id,modelValue:t(v),"onUpdate:modelValue":s[1]||(s[1]=ve=>I(v)?v.value=ve:null),name:"speech-provider",value:u.id,title:u.localizedName,description:u.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(n(),i("div",wt,[S(t(ke),{class:"flex items-center gap-3 rounded-lg p-4",border:"2 dashed neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-800",transition:"colors duration-200 ease-in-out",to:"/settings/providers"},{default:N(()=>s[15]||(s[15]=[e("div",{"i-solar:warning-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1),e("div",{class:"flex flex-col"},[e("span",{class:"font-medium"},"No Speech Providers Configured"),e("span",{class:"text-sm text-neutral-400 dark:text-neutral-500"},"Click here to set up your speech providers")],-1),e("div",{"i-solar:arrow-right-line-duotone":"",class:"ml-auto text-xl text-neutral-400 dark:text-neutral-500"},null,-1)])),_:1})]))])]),e("div",null,[t(v)&&t(P)?(n(),i("div",_t,[e("div",St,[e("div",null,[e("h2",Vt,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",Mt,[e("span",null,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),t(A)?(n(),i("div",Ct,[s[16]||(s[16]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):t(E)?(n(),i("div",$t,[s[17]||(s[17]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",Pt,[e("span",Ut,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",Lt,k(t(E)),1)])])):t(L).length===0&&!t(A)?(n(),i("div",qt,[s[18]||(s[18]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",At,[e("span",Rt,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",Et,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):t(L).length>0?(n(),X(t(Ve),{key:3,modelValue:t(b),"onUpdate:modelValue":s[2]||(s[2]=u=>I(b)?b.value=u:null),"search-query":t(q),"onUpdate:searchQuery":s[3]||(s[3]=u=>I(q)?q.value=u:null),items:t(L),searchable:!0,"search-placeholder":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:t(q)}),"search-results-text":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":ce},null,8,["modelValue","search-query","items","search-placeholder","search-no-results-title","search-no-results-description","search-results-text","custom-input-placeholder","expand-button-text","collapse-button-text"])):$("",!0)])])):$("",!0)])]),t(v)?(n(),i("div",Tt,[e("div",zt,[s[29]||(s[29]=e("div",null,[e("h2",{class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"}," Voice Configuration "),e("div",{text:"neutral-400 dark:neutral-500"},[e("span",null,"Customize how your AI assistant speaks")])],-1)),t(w)?(n(),i("div",Bt,[e("div",Ft,[S(t(Q),{class:"w-full rounded-lg p-2.5 text-sm"},{default:N(()=>s[19]||(s[19]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),e("div",It,[S(t(Q),{class:"w-full rounded-lg p-4 text-sm"},{default:N(()=>s[20]||(s[20]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(Q),{class:"w-full rounded-lg p-4 text-sm"},{default:N(()=>s[21]||(s[21]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(Q),{class:"w-full rounded-lg p-4 text-sm"},{default:N(()=>s[22]||(s[22]=[e("div",{class:"h-1lh"},null,-1)])),_:1})]),S(t(Q),{class:"w-full rounded-lg p-3 text-sm"},{default:N(()=>s[23]||(s[23]=[e("div",{class:"h-1lh"},null,-1)])),_:1})])])):t(a)[t(v)]&&t(a)[t(v)].length>0?(n(),i("div",Nt,[S(t(it),{"search-query":d.value,"onUpdate:searchQuery":s[4]||(s[4]=u=>d.value=u),"voice-id":t(h),"onUpdate:voiceId":s[5]||(s[5]=u=>I(h)?h.value=u:null),voices:(G=t(a)[t(v)])==null?void 0:G.map(u=>({id:u.id,name:u.name,description:u.description,previewURL:u.previewURL,customizable:!1})),searchable:!0,"search-placeholder":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_placeholder"),"search-no-results-title":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices"),"search-no-results-description":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices_description"),"search-results-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_results",{count:0,total:0}),"custom-input-placeholder":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.custom_voice_placeholder"),"expand-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_more"),"collapse-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_less"),"play-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.play_sample"),"pause-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.pause"),"onUpdate:customValue":de},null,8,["search-query","voice-id","voices","search-placeholder","search-no-results-title","search-no-results-description","search-results-text","custom-input-placeholder","expand-button-text","collapse-button-text","play-button-text","pause-button-text"])])):t(T)?(n(),i("div",Dt,[s[25]||(s[25]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",jt,[s[24]||(s[24]=e("span",{class:"font-medium"},"Error loading voices",-1)),e("span",Ot,k(t(T)),1)])])):(n(),i("div",Qt,s[26]||(s[26]=[e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1),e("div",{class:"flex flex-col"},[e("span",{class:"font-medium"},"No voices available"),e("span",{class:"text-sm text-amber-600 dark:text-amber-400"}," No voices were found for this provider. You can enter a custom voice name below. ")],-1)]))),e("div",Ht,[S(t(oe),{modelValue:t(f),"onUpdate:modelValue":s[6]||(s[6]=u=>I(f)?f.value=u:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":u=>`${u}%`},null,8,["modelValue","format-value"]),S(t(ae),{modelValue:t(z),"onUpdate:modelValue":s[7]||(s[7]=u=>I(z)?z.value=u:null),label:"Enable SSML",description:"Enable Speech Synthesis Markup Language for more control over speech output"},null,8,["modelValue"])]),!t(a)[t(v)]||t(a)[t(v)].length===0?(n(),i("div",Gt,[S(t(Se),{modelValue:t(h),"onUpdate:modelValue":s[8]||(s[8]=u=>I(h)?h.value=u:null),type:"text",label:"Voice ID",description:"Enter the voice ID for your custom voice",placeholder:"Enter voice name (e.g., 'Rachel', 'Josh')"},null,8,["modelValue"]),t(v)==="elevenlabs"?(n(),i("div",Jt,[s[28]||(s[28]=e("label",{class:"mb-1 block text-sm font-medium"}," Model ",-1)),j(e("select",{"onUpdate:modelValue":s[9]||(s[9]=u=>I(b)?b.value=u:null),class:"w-full border border-neutral-300 rounded bg-white px-3 py-2 dark:border-neutral-700 dark:bg-neutral-900"},s[27]||(s[27]=[e("option",{value:"eleven_monolingual_v1"}," Monolingual v1 ",-1),e("option",{value:"eleven_multilingual_v1"}," Multilingual v1 ",-1),e("option",{value:"eleven_multilingual_v2"}," Multilingual v2 ",-1)]),512),[[we,t(b)]])])):$("",!0),e("div",Yt,[S(t(oe),{modelValue:t(f),"onUpdate:modelValue":s[10]||(s[10]=u=>I(f)?f.value=u:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":u=>`${u}%`},null,8,["modelValue","format-value"])])])):$("",!0)])])):$("",!0)]),e("div",Kt,[e("div",Wt,[e("h2",Xt,[e("div",Zt,[S(t(_e)),e("div",null,k(t(l)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),e("div",es,[S(t(ae),{modelValue:m.value,"onUpdate:modelValue":s[11]||(s[11]=u=>m.value=u),label:"Use Custom SSML",description:"Enable to input raw SSML instead of plain text"},null,8,["modelValue"]),m.value?j((n(),i("textarea",{key:1,"onUpdate:modelValue":s[13]||(s[13]=u=>U.value=u),placeholder:"Enter SSML text...",border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-48":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","font-mono":"","outline-none":""},null,512)),[[W,U.value]]):j((n(),i("textarea",{key:0,"onUpdate:modelValue":s[12]||(s[12]=u=>_.value=u),placeholder:t(l)("settings.pages.providers.provider.elevenlabs.playground.fields.field.input.placeholder"),border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-24":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","outline-none":""},null,8,ts)),[[W,_.value]]),e("div",ss,[e("button",{border:"neutral-800 dark:neutral-200 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"",text:"neutral-100 dark:neutral-900","py-2":"","text-sm":"",disabled:B.value||!_.value.trim()&&!m.value||m.value&&!U.value.trim()||!t(M),class:C({"opacity-50 cursor-not-allowed":B.value||!_.value.trim()&&!m.value||m.value&&!U.value.trim()||!t(M)}),bg:"neutral-700 dark:neutral-300",onClick:ue},[e("div",os,[s[30]||(s[30]=e("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),e("span",null,k(B.value?t(l)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):t(l)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,ls),y.value?(n(),i("button",{key:0,border:"primary-300 dark:primary-800 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"","py-2":"","text-sm":"",onClick:se},s[31]||(s[31]=[e("div",{flex:"~ row","items-center":"","gap-2":""},[e("div",{"i-solar:stop-circle-bold-duotone":""}),e("span",null,"Stop")],-1)]))):$("",!0)]),y.value?(n(),i("audio",{key:2,ref_key:"audioPlayer",ref:F,src:y.value,controls:"",class:"mt-2 w-full"},null,8,as)):$("",!0)])])])]),s[32]||(s[32]=e("div",{text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},[e("div",{text:"40","i-lucide:volume-2":""})],-1))],64)}}});typeof re=="function"&&re(rs);export{rs as default}; +import{d as O,g as V,m as ne,w as Z,p as ie,c as i,o as n,bx as H,by as Y,a as e,n as me,z as C,bF as K,bG as J,A as j,bA as pe,C as $,D as k,b as S,y as N,bn as ee,h as fe,cc as ge,bJ as W,x as X,i as xe,s as le,bE as be,H as he,bw as ye,e as t,bo as ke,ad as I,bI as we}from"./index-Dlp4W1Zl.js";import{_ as oe,a as ae,b as _e}from"./TestDummyMarker.vue_vue_type_script_setup_true_lang-DUVC_k0v.js";import{_ as Se}from"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import{R as Ve,a as Me}from"./RadioCardDetailManySelect-rPQeY4V8.js";import{_ as Ce}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import{_ as $e}from"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";import"./live2d-zip-loader-C5j9stxV.js";import{u as Pe}from"./providers-BRCa7xUS.js";import{u as Ue,g as Le}from"./speech-DU07zXBj.js";import{b as re}from"./route-block-B_A1xBdJ.js";const qe=O({__name:"AudioSpectrum",props:{stream:null,bars:{default:32},minFreq:{default:60},maxFreq:{default:4e3}},setup(o){const l=o,x=V(Array.from({length:l.bars}).fill(0));ne(()=>{p()}),Z(()=>l.stream,()=>{p()});function p(){if(!l.stream)return;const c=new(window.AudioContext||window.webkitAudioContext),g=c.createMediaStreamSource(l.stream),v=c.createAnalyser();v.fftSize=2048,g.connect(v);const b=v.frequencyBinCount,M=new Uint8Array(b),f=c.sampleRate/v.fftSize,w=Math.floor(l.minFreq/f),P=Math.floor(l.maxFreq/f),L=P-w,A=Math.floor(L/l.bars),E=()=>{try{requestAnimationFrame(E),v.getByteFrequencyData(M);const q=Array.from({length:l.bars}).fill(0);for(let T=0;Tie(c.$slots,"default",{frequencies:x.value})}}),Ae={"h-full":"",flex:"","items-center":"","gap-1":""},Re=5,Ee=O({__name:"AudioSpectrumVisualizer",props:{frequencies:null,barsClass:null},setup(o){const l=o;function x(c,g){return .1+(1-.1)*(c/g)}function p(c,g){const v=x(g,l.frequencies.length);return Math.min(100,Math.max(10,c*100*Re*v))}return(c,g)=>(n(),i("div",Ae,[(n(!0),i(H,null,Y(o.frequencies,(v,b)=>(n(),i("div",{key:b,"h-full":"",flex:"","flex-1":"","items-end":""},[e("div",{transition:"all 100 ease-in-out","mx-auto":"","my-0":"","w-full":"","rounded-full":"",class:C(o.barsClass),style:me({height:`${p(v,b)}%`})},null,6)]))),128))]))}}),Te={class:"p-3"},ze={class:"flex items-start"},Be=["checked","name","value"],Fe={class:"relative mr-3 mt-0.5 flex-shrink-0"},Ie={key:0,class:"i-solar:pause-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},Ne={key:1,class:"i-solar:play-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},De={key:1,class:"mt-auto w-full flex items-center justify-center bg-neutral-50 py-3 text-xs text-neutral-400 italic dark:bg-neutral-800/50 dark:text-neutral-600"},je={class:"flex-1 cursor-pointer"},Oe={class:"flex items-center"},Qe={key:0,class:"mt-1 flex flex-wrap gap-1"},He={key:1,class:"mt-3"},Ge={relative:""},Je={key:0,class:"h-16 px-3 pb-2"},Ye=O({__name:"VoiceCard",props:K({name:null,voice:null,currentlyPlayingId:null,customInputPlaceholder:{default:"Enter custom voice name"},showVisualizer:{type:Boolean,default:!0},audioStream:{default:null}},{"voice-id":{required:!1,default:""},"voice-idModifiers":{},"custom-voice-name":{required:!1,default:""},"custom-voice-nameModifiers":{}}),emits:K(["togglePlayback"],["update:voice-id","update:custom-voice-name"]),setup(o,{emit:l}){const x=o,p=l,c=J(o,"voice-id"),g=J(o,"custom-voice-name");function v(h){return h.previewURL||h.preview_audio_url}function b(h){var w,P,L;const f=[];if((w=h.labels)!=null&&w.gender&&f.push(h.labels.gender),(P=h.labels)!=null&&P.age&&f.push(h.labels.age),(L=h.labels)!=null&&L.accent&&f.push(h.labels.accent),h.languages&&h.languages.length>0){const A=h.languages.map(E=>E.name).join(", ");f.push(A)}return f}function M(){p("togglePlayback",x.voice)}return(h,f)=>(n(),i("label",{border:"2px solid",class:C(["scroll-snap-align-start form_voice-card relative flex flex-col overflow-hidden rounded-xl",[c.value===x.voice.id?"bg-primary-50 dark:bg-primary-900/20 border-primary-100 dark:border-primary-900 hover:border-primary-500/30 dark:hover:border-primary-400/30":"bg-white dark:bg-neutral-900/20 border-neutral-100 dark:border-neutral-900 hover:border-primary-500/30 dark:hover:border-primary-400/30",c.value===x.voice.id?"form_voice-card-active":""]]),transition:"all duration-200 ease-in-out"},[e("div",Te,[e("div",ze,[j(e("input",{"onUpdate:modelValue":f[0]||(f[0]=w=>c.value=w),checked:c.value===x.voice.id,type:"radio",name:o.name,value:x.voice.id,class:"absolute cursor-pointer opacity-0"},null,8,Be),[[pe,c.value]]),e("div",Fe,[e("div",{class:C(["size-5 border-2 rounded-full transition-colors duration-200",[c.value===x.voice.id?"border-primary-500 dark:border-primary-400":"border-neutral-300 dark:border-neutral-600"]])},[e("div",{class:C(["absolute left-1/2 top-1/2 size-3 rounded-full transition-opacity duration-200 -translate-x-1/2 -translate-y-1/2",[c.value===x.voice.id?"opacity-100 bg-primary-500 dark:bg-primary-400":"opacity-0"]])},null,2)],2)]),v(o.voice)?(n(),i("button",{key:0,absolute:"","right-0":"",top:"0","z-100":"",class:C(["translate-x-[-50%] translate-y-[50%]",[o.currentlyPlayingId===o.voice.id?"text-white dark:text-white":""]]),onClick:M},[o.currentlyPlayingId===o.voice.id?(n(),i("div",Ie)):(n(),i("div",Ne))],2)):(n(),i("div",De," No preview available ")),e("div",je,[e("div",Oe,[e("span",{class:C(["line-clamp-1 font-medium",[c.value===o.voice.id?"text-neutral-700 dark:text-neutral-300":"text-neutral-700 dark:text-neutral-400"]])},k(o.voice.name),3)]),b(o.voice).length>0?(n(),i("div",Qe,[(n(!0),i(H,null,Y(b(o.voice),(w,P)=>(n(),i("span",{key:P,class:C(["inline-flex items-center rounded-md px-1.5 py-0.5 text-xs",[c.value===o.voice.id?"bg-primary-100 text-primary-700 dark:bg-primary-900/30 dark:text-primary-400":"bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300"]])},k(w),3))),128))])):$("",!0),o.voice.customizable&&c.value===o.voice.id?(n(),i("div",He,[S($e,{modelValue:g.value,"onUpdate:modelValue":f[1]||(f[1]=w=>g.value=w),type:"text",class:"w-full border border-neutral-300 rounded bg-white px-2 py-1 text-sm dark:border-neutral-700 dark:bg-neutral-900",placeholder:o.customInputPlaceholder},null,8,["modelValue","placeholder"])])):$("",!0),o.voice.description?(n(),i("div",{key:2,class:C(["line-clamp-2 mt-1 text-xs",[c.value===o.voice.id?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]])},k(o.voice.description),3)):$("",!0)])])]),e("div",Ge,[S(Ce,null,{default:N(()=>[o.showVisualizer&&o.currentlyPlayingId===o.voice.id&&o.audioStream?(n(),i("div",Je,[S(qe,{stream:o.audioStream,bars:24,"min-freq":60,"max-freq":4e3},{default:N(({frequencies:w})=>[S(Ee,{frequencies:w,"bars-class":c.value===o.voice.id?"bg-primary-500 dark:bg-primary-400":"bg-neutral-400 dark:bg-neutral-600"},null,8,["frequencies","bars-class"])]),_:1},8,["stream"])])):$("",!0)]),_:1})])],2))}}),Ke=ee(Ye,[["__scopeId","data-v-dbab964e"]]),We={class:"voice-preview-player"},Xe={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},Ze=["placeholder"],et={class:"mt-4 space-y-2"},tt={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},st={key:1,class:"flex items-center gap-3 border border-2 border-amber-200 rounded-xl bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},lt={class:"flex flex-col"},ot={class:"font-medium"},at={class:"text-sm text-amber-600 dark:text-amber-400"},rt={class:"relative"},nt=O({__name:"VoiceCardManySelect",props:K({voices:null,searchable:{type:Boolean,default:!0},searchPlaceholder:{default:"Search voices..."},searchNoResultsTitle:{default:"No voices found"},searchNoResultsDescription:{default:"Try a different search term"},searchResultsText:{default:"{count} of {total} voices"},customInputPlaceholder:{default:"Enter custom voice name"},expandButtonText:{default:"Show more"},collapseButtonText:{default:"Show less"},playButtonText:{default:"Play sample"},pauseButtonText:{default:"Pause"},showVisualizer:{type:Boolean,default:!0}},{"search-query":{required:!1,default:""},"search-queryModifiers":{},"voice-id":{required:!1,default:""},"voice-idModifiers":{}}),emits:["update:search-query","update:voice-id"],setup(o){const l=o,x=V(!1),p=V(),c=V(new Map),g=V(new Map),v=V(new Map),b=V(new Map),M=V(null);function h(){return M.value||(M.value=new(window.AudioContext||window.webkitAudioContext)),M.value}const f=J(o,"search-query"),w=J(o,"voice-id"),P=fe(()=>{if(!f.value)return l.voices;const a=f.value.toLowerCase();return l.voices.filter(r=>{const d=r.name.toLowerCase().includes(a),m=r.description&&r.description.toLowerCase().includes(a),_=r.tags&&r.tags.some(y=>y.toLowerCase().includes(a)),U=r.labels&&Object.values(r.labels).some(y=>typeof y=="string"&&y.toLowerCase().includes(a)),B=r.languages&&r.languages.some(y=>y.name.toLowerCase().includes(a)||y.code.toLowerCase().includes(a));return d||m||_||U||B})});function L(a){return a.previewURL||a.preview_audio_url}function A(a){const r=L(a);if(!r)return null;if(c.value.has(a.id))return c.value.get(a.id)||null;const d=new Audio(r);return d.crossOrigin="anonymous",d.preload="auto",d.addEventListener("ended",()=>{if(p.value===a.id){p.value=void 0;const m=g.value.get(a.id);m&&(m.getTracks().forEach(_=>_.stop()),g.value.delete(a.id))}}),c.value.set(a.id,d),d}function E(a,r){try{if(g.value.has(r))return g.value.get(r)||null;const d=h();if(b.value.has(r)){const B=b.value.get(r),y=d.createMediaStreamDestination();B.connect(y);const F=y.stream;return g.value.set(r,F),F}const m=d.createMediaElementSource(a);b.value.set(r,m),m.connect(d.destination);const _=d.createMediaStreamDestination();m.connect(_);const U=_.stream;return g.value.set(r,U),U}catch(d){return console.error("Failed to create audio stream for visualizer:",d),null}}function q(a){try{if(!L(a))return;const d=A(a);if(!d)return;if(p.value===a.id){d.pause(),p.value=void 0;const m=g.value.get(a.id);m&&(m.getTracks().forEach(_=>_.stop()),g.value.delete(a.id));return}if(p.value){const m=c.value.get(p.value);m&&m.pause();const _=g.value.get(p.value);_&&(_.getTracks().forEach(U=>U.stop()),g.value.delete(p.value))}l.showVisualizer&&!g.value.has(a.id)&&E(d,a.id),d.currentTime=0,d.play().catch(m=>{console.error("Failed to play audio:",m)}),p.value=a.id}catch(r){console.error(r),p.value=void 0}}function T(){c.value.forEach(a=>{a.pause(),a.src=""}),c.value.clear(),g.value.forEach(a=>{a.getTracks().forEach(r=>r.stop())}),g.value.clear(),v.value.forEach(a=>{a.state!=="closed"&&a.close()}),v.value.clear(),b.value.clear(),p.value=void 0}Z(f,()=>{if(p.value){const a=c.value.get(p.value);a&&a.pause();const r=g.value.get(p.value);r&&(r.getTracks().forEach(d=>d.stop()),g.value.delete(p.value)),p.value=void 0}}),ge(T);const z=V("");return(a,r)=>(n(),i("div",We,[o.searchable?(n(),i("div",Xe,[r[4]||(r[4]=e("div",{class:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"},[e("div",{"i-solar:magnifer-line-duotone":"",class:"text-neutral-500 dark:text-neutral-400"})],-1)),j(e("input",{"onUpdate:modelValue":r[0]||(r[0]=d=>f.value=d),type:"search",class:"w-full rounded-xl p-2.5 pl-10 text-sm outline-none",border:"focus:primary-100 dark:focus:primary-400/50 2 solid neutral-200 dark:neutral-800",transition:"all duration-200 ease-in-out",bg:"white dark:neutral-900",placeholder:o.searchPlaceholder},null,8,Ze),[[W,f.value]])])):$("",!0),e("div",et,[f.value?(n(),i("div",tt,k(o.searchResultsText.replace("{count}",P.value.length.toString()).replace("{total}",o.voices.length.toString())),1)):$("",!0),f.value&&P.value.length===0?(n(),i("div",st,[r[5]||(r[5]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",lt,[e("span",ot,k(o.searchNoResultsTitle),1),e("span",at,k(o.searchNoResultsDescription.replace("{query}",f.value)),1)])])):$("",!0),e("div",rt,[e("div",{class:C(["scrollbar-hide grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto",[x.value?"grid-cols-1 md:grid-cols-2 grid-flow-row auto-cols-auto":""]]),transition:"all duration-200 ease-in-out",style:{"scroll-snap-type":"x mandatory"}},[(n(!0),i(H,null,Y(P.value,d=>(n(),X(Ke,{key:d.id,"voice-id":w.value,"onUpdate:voiceId":r[1]||(r[1]=m=>w.value=m),"custom-voice-name":z.value,"onUpdate:customVoiceName":r[2]||(r[2]=m=>z.value=m),name:"voice",voice:d,"currently-playing-id":p.value,"custom-input-placeholder":o.customInputPlaceholder,"show-visualizer":o.showVisualizer,"audio-stream":g.value.get(d.id),onTogglePlayback:q},null,8,["voice-id","custom-voice-name","voice","currently-playing-id","custom-input-placeholder","show-visualizer","audio-stream"]))),128))],2),e("div",{bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"",class:C([x.value?"w-full":"mt-4 w-full rounded-lg"])},[e("button",{"w-full":"",flex:"","items-center":"","justify-center":"","gap-2":"","rounded-lg":"","py-2":"",transition:"all duration-200 ease-in-out",class:C([x.value?"bg-primary-500 hover:bg-primary-600 text-white":"bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800"]),onClick:r[3]||(r[3]=d=>x.value=!x.value)},[e("span",null,k(x.value?o.collapseButtonText:o.expandButtonText),1),e("div",{class:C([x.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),it=ee(nt,[["__scopeId","data-v-070104a7"]]),ut=O({__name:"Skeleton",props:{animation:{default:"pulse"}},setup(o){const l=o;return(x,p)=>(n(),i("div",{class:C(["skeleton",l.animation!=="none"?`skeleton-${l.animation}`:""]),bg:"neutral-200 dark:neutral-800",overflow:"hidden"},[ie(x.$slots,"default",{},void 0,!0)],2))}}),Q=ee(ut,[["__scopeId","data-v-f404da2a"]]),dt={flex:"~ row","items-center":"","gap-2":"",initial:{opacity:0,x:10},enter:{opacity:1,x:0},leave:{opacity:0,x:-10},duration:250},ct={relative:""},vt={absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},mt={text:"neutral-300 dark:neutral-500","text-nowrap":""},pt={"text-nowrap":"","text-3xl":"","font-semibold":""},ft={flex:"~ col md:row gap-6"},gt={bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4",class:"w-full md:w-[40%]"},xt={flex:"~ col gap-4"},bt={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},ht={text:"neutral-400 dark:neutral-500"},yt={"max-w-full":""},kt={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},wt={key:1},_t={key:0},St={flex:"~ col gap-4"},Vt={class:"text-lg md:text-2xl"},Mt={text:"neutral-400 dark:neutral-400"},Ct={key:0,class:"flex items-center justify-center py-4"},$t={key:1,class:"flex items-center gap-3 border border-red-200 rounded-lg bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20"},Pt={class:"flex flex-col"},Ut={class:"font-medium"},Lt={class:"text-sm text-red-600 dark:text-red-400"},qt={key:2,class:"flex items-center gap-3 border border-amber-200 rounded-lg bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},At={class:"flex flex-col"},Rt={class:"font-medium"},Et={class:"text-sm text-amber-600 dark:text-amber-400"},Tt={key:0},zt={flex:"~ col gap-4"},Bt={key:0},Ft={class:"flex flex-col gap-4"},It={flex:"~ row gap-4"},Nt={key:1,class:"space-y-6"},Dt={key:2,class:"flex items-center gap-3 border border-2 border-red-200 rounded-lg bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20"},jt={class:"flex flex-col"},Ot={class:"text-sm text-red-600 dark:text-red-400"},Qt={key:3,class:"flex items-center gap-3 border border-2 border-amber-200 rounded-lg bg-amber-50 p-4 dark:border-amber-800 dark:bg-amber-900/20"},Ht={flex:"~ col gap-4"},Gt={key:4,class:"mt-2 space-y-6"},Jt={key:0},Yt={flex:"~ col gap-4"},Kt={flex:"~ col gap-6",class:"w-full md:w-[60%]"},Wt={"w-full":"","rounded-xl":""},Xt={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},Zt={class:"inline-flex items-center gap-4"},es={flex:"~ col gap-4"},ts=["placeholder"],ss={flex:"~ row","gap-4":""},ls=["disabled"],os={flex:"~ row","items-center":"","gap-2":""},as=["src"],rs=O({__name:"speech",setup(o){const{t:l}=xe(),x=Pe(),p=Ue(),{availableProviders:c,availableAudioSpeechProvidersMetadata:g}=le(x),{activeSpeechProvider:v,activeSpeechModel:b,activeSpeechVoice:M,activeSpeechVoiceId:h,pitch:f,isLoadingSpeechProviderVoices:w,supportsModelListing:P,providerModels:L,isLoadingActiveProviderModels:A,activeProviderModelError:E,modelSearchQuery:q,speechProviderError:T,ssmlEnabled:z,availableVoices:a}=le(p),r=be(),d=V(""),m=V(!1),_=V("Hello, my name is AI Assistant"),U=V(""),B=V(!1),y=V(""),F=V(null),te=V("");ne(async()=>{await p.loadVoicesForProvider(v.value),await x.loadModelsForConfiguredProviders()}),Z(v,async()=>{await p.loadVoicesForProvider(v.value),await x.loadModelsForConfiguredProviders()});async function ue(){if(!_.value.trim()&&!m.value||m.value&&!U.value.trim())return;if(!b.value){console.error("No model selected");return}if(!M.value){console.error("No voice selected");return}const R=x.getProviderInstance(v.value);if(!R){console.error("Failed to initialize speech provider");return}const s=x.getProviderConfig(v.value);B.value=!0,te.value="";try{y.value&&se();const D=m.value?U.value:p.generateSSML(_.value,M.value,{...s,pitch:f.value}),G=await Le({...R.speech(b.value,s),input:D,voice:M.value.id});y.value=URL.createObjectURL(new Blob([G])),setTimeout(()=>{F.value&&F.value.play()},100)}catch(D){console.error("Error generating speech:",D),te.value=D instanceof Error?D.message:"An unknown error occurred"}finally{B.value=!1}}function se(){F.value&&(F.value.pause(),F.value.currentTime=0),y.value&&(URL.revokeObjectURL(y.value),y.value="")}he(()=>{y.value&&URL.revokeObjectURL(y.value)});function de(R){M.value={id:R,name:R,description:R,previewURL:R,languages:[{code:"en",title:"English"}],provider:v.value,gender:"male"}}function ce(R){b.value=R}return(R,s)=>{var G;const D=ye("motion");return n(),i(H,null,[j((n(),i("div",dt,[e("button",{onClick:s[0]||(s[0]=u=>t(r).back())},s[14]||(s[14]=[e("div",{"i-solar:alt-arrow-left-line-duotone":"","text-xl":""},null,-1)])),e("h1",ct,[e("div",vt,[e("span",mt,k(t(l)("settings.pages.modules.title")),1)]),e("div",pt,k(t(l)("settings.pages.modules.speech.title")),1)])])),[[D]]),e("div",ft,[e("div",gt,[e("div",null,[e("div",xt,[e("div",null,[e("h2",bt,k(t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.title")),1),e("div",ht,[e("span",null,k(t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.description")),1)])]),e("div",yt,[t(c).length>0?(n(),i("fieldset",kt,[(n(!0),i(H,null,Y(t(g),u=>(n(),X(t(Me),{id:u.id,key:u.id,modelValue:t(v),"onUpdate:modelValue":s[1]||(s[1]=ve=>I(v)?v.value=ve:null),name:"speech-provider",value:u.id,title:u.localizedName,description:u.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(n(),i("div",wt,[S(t(ke),{class:"flex items-center gap-3 rounded-lg p-4",border:"2 dashed neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-800",transition:"colors duration-200 ease-in-out",to:"/settings/providers"},{default:N(()=>s[15]||(s[15]=[e("div",{"i-solar:warning-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1),e("div",{class:"flex flex-col"},[e("span",{class:"font-medium"},"No Speech Providers Configured"),e("span",{class:"text-sm text-neutral-400 dark:text-neutral-500"},"Click here to set up your speech providers")],-1),e("div",{"i-solar:arrow-right-line-duotone":"",class:"ml-auto text-xl text-neutral-400 dark:text-neutral-500"},null,-1)])),_:1})]))])]),e("div",null,[t(v)&&t(P)?(n(),i("div",_t,[e("div",St,[e("div",null,[e("h2",Vt,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",Mt,[e("span",null,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),t(A)?(n(),i("div",Ct,[s[16]||(s[16]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):t(E)?(n(),i("div",$t,[s[17]||(s[17]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",Pt,[e("span",Ut,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",Lt,k(t(E)),1)])])):t(L).length===0&&!t(A)?(n(),i("div",qt,[s[18]||(s[18]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",At,[e("span",Rt,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",Et,k(t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):t(L).length>0?(n(),X(t(Ve),{key:3,modelValue:t(b),"onUpdate:modelValue":s[2]||(s[2]=u=>I(b)?b.value=u:null),"search-query":t(q),"onUpdate:searchQuery":s[3]||(s[3]=u=>I(q)?q.value=u:null),items:t(L),searchable:!0,"search-placeholder":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:t(q)}),"search-results-text":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":t(l)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":ce},null,8,["modelValue","search-query","items","search-placeholder","search-no-results-title","search-no-results-description","search-results-text","custom-input-placeholder","expand-button-text","collapse-button-text"])):$("",!0)])])):$("",!0)])]),t(v)?(n(),i("div",Tt,[e("div",zt,[s[29]||(s[29]=e("div",null,[e("h2",{class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"}," Voice Configuration "),e("div",{text:"neutral-400 dark:neutral-500"},[e("span",null,"Customize how your AI assistant speaks")])],-1)),t(w)?(n(),i("div",Bt,[e("div",Ft,[S(t(Q),{class:"w-full rounded-lg p-2.5 text-sm"},{default:N(()=>s[19]||(s[19]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),e("div",It,[S(t(Q),{class:"w-full rounded-lg p-4 text-sm"},{default:N(()=>s[20]||(s[20]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(Q),{class:"w-full rounded-lg p-4 text-sm"},{default:N(()=>s[21]||(s[21]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(Q),{class:"w-full rounded-lg p-4 text-sm"},{default:N(()=>s[22]||(s[22]=[e("div",{class:"h-1lh"},null,-1)])),_:1})]),S(t(Q),{class:"w-full rounded-lg p-3 text-sm"},{default:N(()=>s[23]||(s[23]=[e("div",{class:"h-1lh"},null,-1)])),_:1})])])):t(a)[t(v)]&&t(a)[t(v)].length>0?(n(),i("div",Nt,[S(t(it),{"search-query":d.value,"onUpdate:searchQuery":s[4]||(s[4]=u=>d.value=u),"voice-id":t(h),"onUpdate:voiceId":s[5]||(s[5]=u=>I(h)?h.value=u:null),voices:(G=t(a)[t(v)])==null?void 0:G.map(u=>({id:u.id,name:u.name,description:u.description,previewURL:u.previewURL,customizable:!1})),searchable:!0,"search-placeholder":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_placeholder"),"search-no-results-title":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices"),"search-no-results-description":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices_description"),"search-results-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_results",{count:0,total:0}),"custom-input-placeholder":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.custom_voice_placeholder"),"expand-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_more"),"collapse-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_less"),"play-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.play_sample"),"pause-button-text":t(l)("settings.pages.modules.speech.sections.section.provider-voice-selection.pause"),"onUpdate:customValue":de},null,8,["search-query","voice-id","voices","search-placeholder","search-no-results-title","search-no-results-description","search-results-text","custom-input-placeholder","expand-button-text","collapse-button-text","play-button-text","pause-button-text"])])):t(T)?(n(),i("div",Dt,[s[25]||(s[25]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",jt,[s[24]||(s[24]=e("span",{class:"font-medium"},"Error loading voices",-1)),e("span",Ot,k(t(T)),1)])])):(n(),i("div",Qt,s[26]||(s[26]=[e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1),e("div",{class:"flex flex-col"},[e("span",{class:"font-medium"},"No voices available"),e("span",{class:"text-sm text-amber-600 dark:text-amber-400"}," No voices were found for this provider. You can enter a custom voice name below. ")],-1)]))),e("div",Ht,[S(t(oe),{modelValue:t(f),"onUpdate:modelValue":s[6]||(s[6]=u=>I(f)?f.value=u:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":u=>`${u}%`},null,8,["modelValue","format-value"]),S(t(ae),{modelValue:t(z),"onUpdate:modelValue":s[7]||(s[7]=u=>I(z)?z.value=u:null),label:"Enable SSML",description:"Enable Speech Synthesis Markup Language for more control over speech output"},null,8,["modelValue"])]),!t(a)[t(v)]||t(a)[t(v)].length===0?(n(),i("div",Gt,[S(t(Se),{modelValue:t(h),"onUpdate:modelValue":s[8]||(s[8]=u=>I(h)?h.value=u:null),type:"text",label:"Voice ID",description:"Enter the voice ID for your custom voice",placeholder:"Enter voice name (e.g., 'Rachel', 'Josh')"},null,8,["modelValue"]),t(v)==="elevenlabs"?(n(),i("div",Jt,[s[28]||(s[28]=e("label",{class:"mb-1 block text-sm font-medium"}," Model ",-1)),j(e("select",{"onUpdate:modelValue":s[9]||(s[9]=u=>I(b)?b.value=u:null),class:"w-full border border-neutral-300 rounded bg-white px-3 py-2 dark:border-neutral-700 dark:bg-neutral-900"},s[27]||(s[27]=[e("option",{value:"eleven_monolingual_v1"}," Monolingual v1 ",-1),e("option",{value:"eleven_multilingual_v1"}," Multilingual v1 ",-1),e("option",{value:"eleven_multilingual_v2"}," Multilingual v2 ",-1)]),512),[[we,t(b)]])])):$("",!0),e("div",Yt,[S(t(oe),{modelValue:t(f),"onUpdate:modelValue":s[10]||(s[10]=u=>I(f)?f.value=u:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":u=>`${u}%`},null,8,["modelValue","format-value"])])])):$("",!0)])])):$("",!0)]),e("div",Kt,[e("div",Wt,[e("h2",Xt,[e("div",Zt,[S(t(_e)),e("div",null,k(t(l)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),e("div",es,[S(t(ae),{modelValue:m.value,"onUpdate:modelValue":s[11]||(s[11]=u=>m.value=u),label:"Use Custom SSML",description:"Enable to input raw SSML instead of plain text"},null,8,["modelValue"]),m.value?j((n(),i("textarea",{key:1,"onUpdate:modelValue":s[13]||(s[13]=u=>U.value=u),placeholder:"Enter SSML text...",border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-48":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","font-mono":"","outline-none":""},null,512)),[[W,U.value]]):j((n(),i("textarea",{key:0,"onUpdate:modelValue":s[12]||(s[12]=u=>_.value=u),placeholder:t(l)("settings.pages.providers.provider.elevenlabs.playground.fields.field.input.placeholder"),border:"neutral-100 dark:neutral-800 solid 2 focus:neutral-200 dark:focus:neutral-700",transition:"all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800 focus:neutral-50 dark:focus:neutral-900","h-24":"","w-full":"","rounded-lg":"","px-3":"","py-2":"","text-sm":"","outline-none":""},null,8,ts)),[[W,_.value]]),e("div",ss,[e("button",{border:"neutral-800 dark:neutral-200 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"",text:"neutral-100 dark:neutral-900","py-2":"","text-sm":"",disabled:B.value||!_.value.trim()&&!m.value||m.value&&!U.value.trim()||!t(M),class:C({"opacity-50 cursor-not-allowed":B.value||!_.value.trim()&&!m.value||m.value&&!U.value.trim()||!t(M)}),bg:"neutral-700 dark:neutral-300",onClick:ue},[e("div",os,[s[30]||(s[30]=e("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),e("span",null,k(B.value?t(l)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):t(l)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,ls),y.value?(n(),i("button",{key:0,border:"primary-300 dark:primary-800 solid 2",transition:"border duration-250 ease-in-out","rounded-lg":"","px-4":"","py-2":"","text-sm":"",onClick:se},s[31]||(s[31]=[e("div",{flex:"~ row","items-center":"","gap-2":""},[e("div",{"i-solar:stop-circle-bold-duotone":""}),e("span",null,"Stop")],-1)]))):$("",!0)]),y.value?(n(),i("audio",{key:2,ref_key:"audioPlayer",ref:F,src:y.value,controls:"",class:"mt-2 w-full"},null,8,as)):$("",!0)])])])]),s[32]||(s[32]=e("div",{text:"neutral-200/50 dark:neutral-500/20","pointer-events-none":"",fixed:"","bottom-0":"","right-0":"","z--1":"","translate-x-10":"","translate-y-10":""},[e("div",{text:"40","i-lucide:volume-2":""})],-1))],64)}}});typeof re=="function"&&re(rs);export{rs as default}; diff --git a/assets/speech-CUKri9wm.js b/assets/speech-DU07zXBj.js similarity index 98% rename from assets/speech-CUKri9wm.js rename to assets/speech-DU07zXBj.js index 5362bbdb7e8e4220c2b5e9bf936cf6fcfb74979d..fbe27be2f92baae67eb376b2e497a55e8ba30dad 100644 --- a/assets/speech-CUKri9wm.js +++ b/assets/speech-DU07zXBj.js @@ -1,2 +1,2 @@ -import{f as ie,cb as h,g as S,h as m,w as q,m as oe}from"./index-rD0Uu1v9.js";import{r as ce,a as le,b as ue,d as de,u as me}from"./providers-Dg3FpvfZ.js";var ge=async e=>(e.fetch??globalThis.fetch)(ce("audio/speech",e.baseURL),{body:ue(e),headers:le({"Content-Type":"application/json",...e.headers},e.apiKey),method:"POST",signal:e.abortSignal}).then(de).then(async t=>t.arrayBuffer());const pe=/["&'<>`]/g,he=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,fe=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,ve=/[|\\{}()[\]^$+*?.]/g,j=new WeakMap;function z(e,t){if(e=e.replace(t.subset?ye(t.subset):pe,n),t.subset||t.escapeOnly)return e;return e.replace(he,r).replace(fe,n);function r(a,i,u){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,u.charCodeAt(i+2),t)}function n(a,i,u){return t.format(a.charCodeAt(0),u.charCodeAt(i+1),t)}}function ye(e){let t=j.get(e);return t||(t=Se(e),j.set(e,t)),t}function Se(e){const t=[];let r=-1;for(;++r",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",permil:"‰",lsaquo:"‹",rsaquo:"›",euro:"€"},Oe=["cent","copy","divide","gt","lt","not","para","times"],B={}.hasOwnProperty,R={};let b;for(b in M)B.call(M,b)&&(R[M[b]]=b);const Pe=/[^\dA-Za-z]/;function qe(e,t,r,n){const a=String.fromCharCode(e);if(B.call(R,a)){const i=R[a],u="&"+i;return r&&Ee.includes(i)&&!Oe.includes(i)&&(!n||t&&t!==61&&Pe.test(String.fromCharCode(t)))?u:u+";"}return""}function Me(e,t,r){let n=Ae(e,t,r.omitOptionalSemicolons),a;if((r.useNamedReferences||r.useShortestReferences)&&(a=qe(e,t,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!a)&&r.useShortestReferences){const i=we(e,t,r.omitOptionalSemicolons);i.length/g,Ue=[">"];function $e(e){return""}function je(e){return""}const Ne=[" ",` +import{f as ie,cb as h,g as S,h as m,w as q,m as oe}from"./index-Dlp4W1Zl.js";import{r as ce,a as le,b as ue,d as de,u as me}from"./providers-BRCa7xUS.js";var ge=async e=>(e.fetch??globalThis.fetch)(ce("audio/speech",e.baseURL),{body:ue(e),headers:le({"Content-Type":"application/json",...e.headers},e.apiKey),method:"POST",signal:e.abortSignal}).then(de).then(async t=>t.arrayBuffer());const pe=/["&'<>`]/g,he=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,fe=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,ve=/[|\\{}()[\]^$+*?.]/g,j=new WeakMap;function z(e,t){if(e=e.replace(t.subset?ye(t.subset):pe,n),t.subset||t.escapeOnly)return e;return e.replace(he,r).replace(fe,n);function r(a,i,u){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,u.charCodeAt(i+2),t)}function n(a,i,u){return t.format(a.charCodeAt(0),u.charCodeAt(i+1),t)}}function ye(e){let t=j.get(e);return t||(t=Se(e),j.set(e,t)),t}function Se(e){const t=[];let r=-1;for(;++r",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",permil:"‰",lsaquo:"‹",rsaquo:"›",euro:"€"},Oe=["cent","copy","divide","gt","lt","not","para","times"],B={}.hasOwnProperty,R={};let b;for(b in M)B.call(M,b)&&(R[M[b]]=b);const Pe=/[^\dA-Za-z]/;function qe(e,t,r,n){const a=String.fromCharCode(e);if(B.call(R,a)){const i=R[a],u="&"+i;return r&&Ee.includes(i)&&!Oe.includes(i)&&(!n||t&&t!==61&&Pe.test(String.fromCharCode(t)))?u:u+";"}return""}function Me(e,t,r){let n=Ae(e,t,r.omitOptionalSemicolons),a;if((r.useNamedReferences||r.useShortestReferences)&&(a=qe(e,t,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!a)&&r.useShortestReferences){const i=we(e,t,r.omitOptionalSemicolons);i.length/g,Ue=[">"];function $e(e){return""}function je(e){return""}const Ne=[" ",` `," ",'"',"&","'","/","<","=",">"];function A(e){return y(e,Ne)}function N(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,a=r.indexOf(t);for(;a!==-1;)n++,a=r.indexOf(t,a+t.length);return n}function T(e,t){const r=String(e);let n=t.options.quote||'"';if(t.options.quoteSmart){const a=n==='"'?"'":'"';N(r,n)>N(r,a)&&(n=a)}return n+y(r,["<","&",n])+n}function ke(e,t){const r=A(e.name),n=e.public,a=e.system;let i=""}const De={}.hasOwnProperty;function Ie(e,t){const r=A(e.name),n=K(e,t),a=e.attributes||{},i=n?!1:t.options.closeEmptyElements,u=[];let f;for(f in a)if(De.call(a,f)){const p=a[f];p!=null&&u.push(A(f)+"="+T(p,t))}return"<"+r+(u.length===0?"":" "+u.join(" "))+(i?(t.options.tightClose?"":" ")+"/":"")+">"+n+(i?"":"")}const ze=/\?>/g,Be=[">"];function Ve(e){const t=A(e.name)||"x",r=y(e.value,Be,ze);return""}const He=["&","<"];function V(e){return y(e.value,He)}function Ke(e,t){return t.options.allowDangerousXml?e.value:V(e)}const Ye={}.hasOwnProperty,k={cdata:$e,comment:je,doctype:ke,element:Ie,instruction:Ve,raw:Ke,root:K,text:V};function H(e,t){const r=e&&e.type;if(!r)throw new Error("Expected node, not `"+e+"`");if(!Ye.call(k,r))throw new Error("Cannot compile unknown node `"+r+"`");const n=k[r];return n(e,t)}function K(e,t){const r=e&&e.children||[];let n=-1;const a=[];for(;++n{const e=me(),t=h("settings/speech/active-provider",""),r=h("settings/speech/active-model","eleven_multilingual_v2"),n=h("settings/speech/voice",""),a=S(),i=h("settings/speech/pitch",0),u=h("settings/speech/rate",1),f=h("settings/speech/ssml-enabled",!1),p=S(!1),x=S(null),v=S({}),U=h("settings/speech/language","en-US"),w=S(""),Y=m(()=>e.availableProviders.filter(s=>O(s)).map(s=>e.getProviderMetadata(s))),G=m(()=>{var s;return((s=e.getProviderMetadata(t.value))==null?void 0:s.capabilities.listModels)!==void 0}),E=m(()=>e.getModelsForProvider(t.value)),X=m(()=>e.isLoadingModels[t.value]||!1),Z=m(()=>e.modelLoadError[t.value]||null),_=m(()=>{if(!w.value.trim())return E.value;const s=w.value.toLowerCase().trim();return E.value.filter(o=>o.name.toLowerCase().includes(s)||o.id.toLowerCase().includes(s)||o.description&&o.description.toLowerCase().includes(s))}),Q=m(()=>["elevenlabs","microsoft-speech","azure-speech","google"].includes(t.value)),W=m(()=>Object.keys(L)),J=m(()=>{const s=U.value;return!s||!L[s]?[]:L[s].map(o=>({id:Ze[o],name:o,provider:"elevenlabs",language:s}))});function O(s){return["elevenlabs","microsoft-speech","azure-speech","google","amazon"].includes(s)}async function P(s){var o,c;if(!s||!O(s))return[];p.value=!0,x.value=null;try{const l=await((c=(o=e.getProviderMetadata(s).capabilities).listVoices)==null?void 0:c.call(o,e.getProviderConfig(s)))||[];return v.value[s]=l,l}catch(l){return console.error(`Error fetching voices for ${s}:`,l),x.value=l instanceof Error?l.message:"Unknown error",[]}finally{p.value=!1}}function ee(s){return v.value[s]||[]}q(t,async s=>{s&&await P(s)}),oe(()=>{P(t.value).then(()=>{var s;n.value&&(a.value=(s=v.value[t.value])==null?void 0:s.find(o=>o.id===n.value))})}),q(n,s=>{var o;s&&(a.value=(o=v.value[t.value])==null?void 0:o.find(c=>c.id===s))},{immediate:!0}),q(v,s=>{var o;n.value&&(a.value=(o=s[t.value])==null?void 0:o.find(c=>c.id===n.value))},{immediate:!0});async function te(s,o,c,l,g={}){return await ge({...s.speech(o,{...g}),input:c,voice:l})}function re(s,o,c){var $;const l=c==null?void 0:c.pitch,g=c==null?void 0:c.speed,d=c==null?void 0:c.volume,ne={pitch:l!=null?l>0?`+${l}%`:`-${l}%`:void 0,rate:g!=null?g!==1?`${g}`:"1":void 0,volume:d!=null?d>0?`+${d}%`:`${d}%`:void 0},ae=C("speak",{version:"1.0",xmlns:"http://www.w3.org/2001/10/synthesis","xml:lang":(($=o.languages[0])==null?void 0:$.code)||"en-US"},[C("voice",{name:o.id,gender:o.gender||"neutral"},[Object.entries(ne).filter(([_e,se])=>se!=null).length>0?C("prosody",{pitch:l!=null?l>0?`+${l}%`:`-${l}%`:void 0,rate:g!=null?g!==1?`${g}`:"1":void 0,volume:d!=null?d>0?`+${d}%`:`${d}%`:void 0},[s]):s])]);return Ge(ae)}return{activeSpeechProvider:t,activeSpeechModel:r,activeSpeechVoice:a,activeSpeechVoiceId:n,pitch:i,rate:u,ssmlEnabled:f,selectedLanguage:U,isLoadingSpeechProviderVoices:p,speechProviderError:x,availableVoices:v,modelSearchQuery:w,availableSpeechProvidersMetadata:Y,supportsSSML:Q,availableLanguages:W,availableVoicesForLanguage:J,supportsModelListing:G,providerModels:E,isLoadingActiveProviderModels:X,activeProviderModelError:Z,filteredModels:_,speech:te,loadVoicesForProvider:P,getVoicesForProvider:ee,generateSSML:re,isSpeechProvider:O}});export{N as c,ge as g,Je as s,et as u}; diff --git a/assets/stage-DniKT8GJ.js b/assets/stage-DPabq-4P.js similarity index 84% rename from assets/stage-DniKT8GJ.js rename to assets/stage-DPabq-4P.js index d29995096a3a8a905de673d7a3f54b76b8a235ed..c36b721ccd3268d5159dea5694e7e54d233d4a0f 100644 --- a/assets/stage-DniKT8GJ.js +++ b/assets/stage-DPabq-4P.js @@ -1 +1 @@ -import{d as p,u as s,c,b as d,r as i,n as m,e,o as l}from"./index-rD0Uu1v9.js";const x=p({__name:"stage",setup(u){const{top:t,right:o,bottom:a,left:n}=s();return(f,_)=>{const r=i("RouterView");return l(),c("main",{text:"gray-700 dark:gray-200","h-full":"","font-cuteen":"",style:m({paddingTop:`${e(t)}px`,paddingRight:`${e(o)}px`,paddingBottom:`${e(a)}px`,paddingLeft:`${e(n)}px`})},[d(r)],4)}}});export{x as default}; +import{d as p,u as s,c,b as d,r as i,n as m,e,o as l}from"./index-Dlp4W1Zl.js";const x=p({__name:"stage",setup(u){const{top:t,right:o,bottom:a,left:n}=s();return(f,_)=>{const r=i("RouterView");return l(),c("main",{text:"gray-700 dark:gray-200","h-full":"","font-cuteen":"",style:m({paddingTop:`${e(t)}px`,paddingRight:`${e(o)}px`,paddingBottom:`${e(a)}px`,paddingLeft:`${e(n)}px`})},[d(r)],4)}}});export{x as default}; diff --git a/assets/together-ai-DTW1P193.js b/assets/together-ai-BSofzTUT.js similarity index 72% rename from assets/together-ai-DTW1P193.js rename to assets/together-ai-BSofzTUT.js index 9f99b95d1fd3f9d40c67a0e2f3ed80d2951946f0..182712bb1d710374766f2f42ac02c46690a858e0 100644 --- a/assets/together-ai-DTW1P193.js +++ b/assets/together-ai-BSofzTUT.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as h,i as y,bE as U,s as V,h as v,m as $,w as k,x,o as K,y as p,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as z}from"./providers-Dg3FpvfZ.js";import{_ as w,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="together-ai",H=h({__name:"together-ai",setup(S){const{t:d}=y(),_=U(),m=z(),{providers:o}=V(m),n=v(()=>m.getProviderMetadata(a)),i=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,r;m.initializeProvider(a),i.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((r=o.value[a])==null?void 0:r.baseUrl)||""}),k([i,s],()=>{o.value[a]={...o.value[a],apiKey:i.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,r)=>{var c,f;return K(),x(t(R),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:p(()=>{var u;return[l(t(M),{modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=b=>i.value=b),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"togetherapi-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(w),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":r[1]||(r[1]=u=>s.value=u),placeholder:"https://api.together.xyz/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as h,i as y,bE as U,s as V,h as v,m as $,w as k,x,o as K,y as p,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as z}from"./providers-BRCa7xUS.js";import{_ as w,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="together-ai",H=h({__name:"together-ai",setup(S){const{t:d}=y(),_=U(),m=z(),{providers:o}=V(m),n=v(()=>m.getProviderMetadata(a)),i=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,r;m.initializeProvider(a),i.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((r=o.value[a])==null?void 0:r.baseUrl)||""}),k([i,s],()=>{o.value[a]={...o.value[a],apiKey:i.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,r)=>{var c,f;return K(),x(t(R),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon-color":(f=n.value)==null?void 0:f.iconColor,"on-back":()=>t(_).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:p(()=>{var u;return[l(t(M),{modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=b=>i.value=b),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"togetherapi-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(w),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":r[1]||(r[1]=u=>s.value=u),placeholder:"https://api.together.xyz/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});export{H as default}; diff --git a/assets/useIconAnimation-BDdHp70p.js b/assets/useIconAnimation-DMJpspm5.js similarity index 67% rename from assets/useIconAnimation-BDdHp70p.js rename to assets/useIconAnimation-DMJpspm5.js index 43b088cd879434897263d0d4e01287a21bd4fc1a..2028a1c60fc00d78a8b146f14e1ac20173dcca0c 100644 --- a/assets/useIconAnimation-BDdHp70p.js +++ b/assets/useIconAnimation-DMJpspm5.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{g as t,v as u,h as r,m,H as c}from"./index-rD0Uu1v9.js";function p(s){const n=t(!1),o=t(!1),a=t(s),e=u(),i=r(()=>o.value&&!e.disableTransitions&&e.usePageSpecificTransitions);return m(()=>{o.value=!0,requestAnimationFrame(()=>{n.value=!0})}),c(()=>{n.value=!1,o.value=!1}),{iconAnimationStarted:n,showIconAnimation:i,animationIcon:a}}export{p as u}; +import"./live2d-zip-loader-C5j9stxV.js";import{g as t,v as u,h as r,m,H as c}from"./index-Dlp4W1Zl.js";function p(s){const n=t(!1),o=t(!1),a=t(s),e=u(),i=r(()=>o.value&&!e.disableTransitions&&e.usePageSpecificTransitions);return m(()=>{o.value=!0,requestAnimationFrame(()=>{n.value=!0})}),c(()=>{n.value=!1,o.value=!1}),{iconAnimationStarted:n,showIconAnimation:i,animationIcon:a}}export{p as u}; diff --git a/assets/worker-KF4IHpL4.js b/assets/worker-D9VCBMJ0.js similarity index 51% rename from assets/worker-KF4IHpL4.js rename to assets/worker-D9VCBMJ0.js index 1b8622271c0b5514b36e634925aa820cfe7f4650..ab478a44e71501319c6161a02d146992ac793d62 100644 --- a/assets/worker-KF4IHpL4.js +++ b/assets/worker-D9VCBMJ0.js @@ -1,46 +1,46 @@ -var bx=Object.defineProperty;var vx=(bs,Sr,Ln)=>Sr in bs?bx(bs,Sr,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):bs[Sr]=Ln;var re=(bs,Sr,Ln)=>vx(bs,typeof Sr!="symbol"?Sr+"":Sr,Ln);(function(){"use strict";const bs=new Map,Sr=[],Ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=bs.get(e);if(s===void 0)bs.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const i=Sr.indexOf(e);i!==-1&&Sr.splice(i,1);for(let n=0;n{const r=bs.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},cb=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Sr:t;let i;const n=[],o=new Set;for(const l of s){const d=await db(l);typeof d=="string"?n.push({name:l,err:d}):(i||(i=d),i===d&&o.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:d}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);const a=r.filter(l=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,d)=>d==="executionProviders"?a:Reflect.get(l,d)})]},ub="1.21.0";let Iu="warning";const es={wasm:{},webgl:{},webgpu:{},versions:{common:ub},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Iu=e}},get logLevel(){return Iu}};Object.defineProperty(es,"logLevel",{enumerable:!0});const pb=es,hb=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);const o=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,d;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));const p=n*i;let u=0,h=p,w=p*2,_=-1;o==="RGBA"?(u=0,h=p,w=p*2,_=p*3):o==="RGB"?(u=0,h=p,w=p*2):o==="RBG"&&(u=0,w=p,h=p*2);for(let P=0;P{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const u=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let w=0,_=1,P=2,A=3,v=0,y=u,S=u*2,x=-1;a==="RGBA"?(v=0,y=u,S=u*2,x=u*3):a==="RGB"?(v=0,y=u,S=u*2):a==="RBG"&&(v=0,S=u,y=u*2),s=t.createImageData(i,n);for(let g=0;g{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,i=r.norm??{mean:255,bias:0};let n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",d=t*s,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,h=0,w=1,_=2,P=3,A=0,v=d,y=d*2,S=-1;a==="RGB"&&(u=3,h=0,w=1,_=2,P=-1),l==="RGBA"?S=d*3:l==="RBG"?(A=0,y=d,v=d*2):l==="BGR"&&(y=0,v=d,A=d*2);for(let g=0;g{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let o,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const u=d(p);if(u!=null){let h=e.height,w=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,w=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=w}else a.tensorFormat="RGBA",a.height=h,a.width=w;u.drawImage(e,0,0),o=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=u,r!==void 0){const h=l();h.width=u,h.height=p;const w=d(h);if(w!=null)w.putImageData(e,0,0),o=w.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const u=d(p);if(u!=null){const h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),o=u.getImageData(0,0,w,h).data,a.height=h,a.width=w,od(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,u)=>{const h=l(),w=d(h);if(!e||!w)return u();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{h.width=_.width,h.height=_.height,w.drawImage(_,0,0,h.width,h.height);const P=w.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(od(P.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return od(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},_b=(e,r)=>{const{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Gr({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},gb=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Gr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},wb=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Gr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},yb=(e,r,t)=>new Gr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),zn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ha=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Au=!1;const Mb=()=>{if(!Au){Au=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(zn.set("int64",BigInt64Array),ha.set(BigInt64Array,"int64")),r&&(zn.set("uint64",BigUint64Array),ha.set(BigUint64Array,"uint64")),s?(zn.set("float16",t),ha.set(t,"float16")):zn.set("float16",Uint16Array)}},bb=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Gr(e.type,e.data,r);case"cpu-pinned":return new Gr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Gr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Gr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Gr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Gr=class{constructor(r,t,s){Mb();let i,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,i=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=zn.get(i);if(!a)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(i=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const d=zn.get(r);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&d===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${d.name} as data.`);r==="uint64"||r==="int64"?a=d.from(t,BigInt):a=d.from(t)}else if(t instanceof d)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&d!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const d=typeof r[0];if(d==="string")i="string",a=r;else if(d==="boolean")i="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(r instanceof Uint8ClampedArray)i="uint8",a=Uint8Array.from(r);else{const d=ha.get(r.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);i=d,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const o=bb(n);if(this.cpuData&&o!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=n,this.size=o}static async fromImage(r,t){return fb(r,t)}static fromTexture(r,t){return _b(r,t)}static fromGpuBuffer(r,t){return gb(r,t)}static fromMLTensor(r,t){return wb(r,t)}static fromPinnedBuffer(r,t,s){return yb(r,t,s)}toDataURL(r){return hb(this,r)}toImageData(r){return mb(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return vb(this,r)}};const Bn=Gr,Fu=(e,r)=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ou=(e,r)=>{var i;const t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Ou("BEGIN",e)},ld=e=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Ou("END",e)};var xb=Object.freeze({__proto__:null,InferenceSession:class ob{constructor(r){this.handler=r}async run(r,t,s){ad();const i={};let n={};if(typeof r!="object"||r===null||r instanceof Bn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Bn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const d of t){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let d=!1;const p=Object.getOwnPropertyNames(t);for(const u of this.outputNames)if(p.indexOf(u)!==-1){const h=t[u];(h===null||h instanceof Bn)&&(d=!0,o=!1,i[u]=h)}if(d){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const d of this.inputNames)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(o)for(const d of this.outputNames)i[d]=null;const a=await this.handler.run(r,i,n),l={};for(const d in a)if(Object.hasOwnProperty.call(a,d)){const p=a[d];p instanceof Bn?l[d]=p:l[d]=new Bn(p.type,p.data,p.dims)}return ld(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){ad();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let u=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-u,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await cb(o),d=await a.createInferenceSessionHandler(n,l);return ld(),new ob(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Fu,TRACE_FUNC_BEGIN:ad,TRACE_FUNC_END:ld,Tensor:Bn,env:pb,registerBackend:Ln});/*! +var Ax=Object.defineProperty;var Fx=(bs,$r,Ln)=>$r in bs?Ax(bs,$r,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):bs[$r]=Ln;var re=(bs,$r,Ln)=>Fx(bs,typeof $r!="symbol"?$r+"":$r,Ln);(function(){"use strict";const bs=new Map,$r=[],Ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=bs.get(e);if(s===void 0)bs.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const i=$r.indexOf(e);i!==-1&&$r.splice(i,1);for(let n=0;n<$r.length;n++)if(bs.get($r[n]).priority<=t){$r.splice(n,0,e);return}$r.push(e)}return}throw new TypeError("not a valid backend")},Mb=async e=>{const r=bs.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},bb=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?$r:t;let i;const n=[],o=new Set;for(const l of s){const d=await Mb(l);typeof d=="string"?n.push({name:l,err:d}):(i||(i=d),i===d&&o.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:d}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);const a=r.filter(l=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,d)=>d==="executionProviders"?a:Reflect.get(l,d)})]},vb="1.21.0";let Au="warning";const es={wasm:{},webgl:{},webgpu:{},versions:{common:vb},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Au=e}},get logLevel(){return Au}};Object.defineProperty(es,"logLevel",{enumerable:!0});const xb=es,Tb=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);const o=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,d;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));const p=n*i;let u=0,h=p,w=p*2,f=-1;o==="RGBA"?(u=0,h=p,w=p*2,f=p*3):o==="RGB"?(u=0,h=p,w=p*2):o==="RBG"&&(u=0,w=p,h=p*2);for(let P=0;P{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const u=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let w=0,f=1,P=2,A=3,b=0,y=u,$=u*2,T=-1;a==="RGBA"?(b=0,y=u,$=u*2,T=u*3):a==="RGB"?(b=0,y=u,$=u*2):a==="RBG"&&(b=0,$=u,y=u*2),s=t.createImageData(i,n);for(let g=0;g{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,i=r.norm??{mean:255,bias:0};let n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",d=t*s,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,h=0,w=1,f=2,P=3,A=0,b=d,y=d*2,$=-1;a==="RGB"&&(u=3,h=0,w=1,f=2,P=-1),l==="RGBA"?$=d*3:l==="RBG"?(A=0,y=d,b=d*2):l==="BGR"&&(y=0,b=d,A=d*2);for(let g=0;g{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let o,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const u=d(p);if(u!=null){let h=e.height,w=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,w=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=w}else a.tensorFormat="RGBA",a.height=h,a.width=w;u.drawImage(e,0,0),o=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=u,r!==void 0){const h=l();h.width=u,h.height=p;const w=d(h);if(w!=null)w.putImageData(e,0,0),o=w.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const u=d(p);if(u!=null){const h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),o=u.getImageData(0,0,w,h).data,a.height=h,a.width=w,ad(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,u)=>{const h=l(),w=d(h);if(!e||!w)return u();const f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{h.width=f.width,h.height=f.height,w.drawImage(f,0,0,h.width,h.height);const P=w.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(ad(P.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ad(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Cb=(e,r)=>{const{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Gr({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},Sb=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Gr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},$b=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Gr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},kb=(e,r,t)=>new Gr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),zn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ha=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Fu=!1;const Ib=()=>{if(!Fu){Fu=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(zn.set("int64",BigInt64Array),ha.set(BigInt64Array,"int64")),r&&(zn.set("uint64",BigUint64Array),ha.set(BigUint64Array,"uint64")),s?(zn.set("float16",t),ha.set(t,"float16")):zn.set("float16",Uint16Array)}},Ab=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Gr(e.type,e.data,r);case"cpu-pinned":return new Gr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Gr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Gr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Gr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Gr=class{constructor(r,t,s){Ib();let i,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,i=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=zn.get(i);if(!a)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(i=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const d=zn.get(r);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&d===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${d.name} as data.`);r==="uint64"||r==="int64"?a=d.from(t,BigInt):a=d.from(t)}else if(t instanceof d)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&d!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const d=typeof r[0];if(d==="string")i="string",a=r;else if(d==="boolean")i="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(r instanceof Uint8ClampedArray)i="uint8",a=Uint8Array.from(r);else{const d=ha.get(r.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);i=d,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const o=Ab(n);if(this.cpuData&&o!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=n,this.size=o}static async fromImage(r,t){return Pb(r,t)}static fromTexture(r,t){return Cb(r,t)}static fromGpuBuffer(r,t){return Sb(r,t)}static fromMLTensor(r,t){return $b(r,t)}static fromPinnedBuffer(r,t,s){return kb(r,t,s)}toDataURL(r){return Tb(this,r)}toImageData(r){return Eb(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Fb(this,r)}};const Bn=Gr,Ou=(e,r)=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||console.timeStamp(`${e}::ORT::${r}`)},Du=(e,r)=>{var i;const t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Du("BEGIN",e)},dd=e=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Du("END",e)};var Ob=Object.freeze({__proto__:null,InferenceSession:class gb{constructor(r){this.handler=r}async run(r,t,s){ld();const i={};let n={};if(typeof r!="object"||r===null||r instanceof Bn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Bn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const d of t){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let d=!1;const p=Object.getOwnPropertyNames(t);for(const u of this.outputNames)if(p.indexOf(u)!==-1){const h=t[u];(h===null||h instanceof Bn)&&(d=!0,o=!1,i[u]=h)}if(d){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const d of this.inputNames)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(o)for(const d of this.outputNames)i[d]=null;const a=await this.handler.run(r,i,n),l={};for(const d in a)if(Object.hasOwnProperty.call(a,d)){const p=a[d];p instanceof Bn?l[d]=p:l[d]=new Bn(p.type,p.data,p.dims)}return dd(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){ld();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let u=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-u,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await bb(o),d=await a.createInferenceSessionHandler(n,l);return dd(),new gb(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Ou,TRACE_FUNC_BEGIN:ld,TRACE_FUNC_END:dd,Tensor:Bn,env:xb,registerBackend:Ln});/*! * ONNX Runtime Web v1.22.0-dev.20250306-ccf8fdd9ea * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. - */var dd=Object.defineProperty,Tb=Object.getOwnPropertyDescriptor,Eb=Object.getOwnPropertyNames,Pb=Object.prototype.hasOwnProperty,Cb=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),je=(e,r)=>()=>(e&&(r=e(e=0)),r),Ci=(e,r)=>{for(var t in r)dd(e,t,{get:r[t],enumerable:!0})},Sb=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Eb(r))!Pb.call(e,i)&&i!==t&&dd(e,i,{get:()=>r[i],enumerable:!(s=Tb(r,i))||s.enumerable});return e},ma=e=>Sb(dd({},"__esModule",{value:!0}),e),Si,Vs,un,Du,Lu,zu=je(()=>{Si=new Map,Vs=[],un=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Si.get(e);if(s===void 0)Si.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let i=Vs.indexOf(e);i!==-1&&Vs.splice(i,1);for(let n=0;n{let r=Si.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Lu=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Vs:t,i,n=[],o=new Set;for(let l of s){let d=await Du(l);typeof d=="string"?n.push({name:l,err:d}):(i||(i=d),i===d&&o.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:d}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);let a=r.filter(l=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,d)=>d==="executionProviders"?a:Reflect.get(l,d)})]}}),$b=je(()=>{zu()}),Bu,kb=je(()=>{Bu="1.22.0-dev.20250306-aafa8d170a"}),cd,Kr,Ru=je(()=>{kb(),cd="warning",Kr={wasm:{},webgl:{},webgpu:{},versions:{common:Bu},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);cd=e}},get logLevel(){return cd}},Object.defineProperty(Kr,"logLevel",{enumerable:!0})}),Vt,Ib=je(()=>{Ru(),Vt=Kr}),Nu,ju,Ab=je(()=>{Nu=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);let o=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,d;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));let p=n*i,u=0,h=p,w=p*2,_=-1;o==="RGBA"?(u=0,h=p,w=p*2,_=p*3):o==="RGB"?(u=0,h=p,w=p*2):o==="RBG"&&(u=0,w=p,h=p*2);for(let P=0;P{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let u=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,w=0,_=1,P=2,A=3,v=0,y=u,S=u*2,x=-1;a==="RGBA"?(v=0,y=u,S=u*2,x=u*3):a==="RGB"?(v=0,y=u,S=u*2):a==="RBG"&&(v=0,S=u,y=u*2),s=t.createImageData(i,n);for(let g=0;g{pd(),fa=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,i=r.norm??{mean:255,bias:0},n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",d=t*s,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,h=0,w=1,_=2,P=3,A=0,v=d,y=d*2,S=-1;a==="RGB"&&(u=3,h=0,w=1,_=2,P=-1),l==="RGBA"?S=d*3:l==="RBG"?(A=0,y=d,v=d*2):l==="BGR"&&(y=0,v=d,A=d*2);for(let x=0;x{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",o,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let u=d(p);if(u!=null){let h=e.height,w=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,w=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=w}else a.tensorFormat="RGBA",a.height=h,a.width=w;u.drawImage(e,0,0),o=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=u,r!==void 0){let h=l();h.width=u,h.height=p;let w=d(h);if(w!=null)w.putImageData(e,0,0),o=w.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let u=d(p);if(u!=null){let h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),o=u.getImageData(0,0,w,h).data,a.height=h,a.width=w,fa(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,u)=>{let h=l(),w=d(h);if(!e||!w)return u();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{h.width=_.width,h.height=_.height,w.drawImage(_,0,0,h.width,h.height);let P=w.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(fa(P.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return fa(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Vu=(e,r)=>{let{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Br({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},Wu=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Br({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},Gu=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Br({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},Ku=(e,r,t)=>new Br({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),pn,$i,ud,Hu,Ob=je(()=>{pn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),$i=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ud=!1,Hu=()=>{if(!ud){ud=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(pn.set("int64",BigInt64Array),$i.set(BigInt64Array,"int64")),r&&(pn.set("uint64",BigUint64Array),$i.set(BigUint64Array,"uint64")),s?(pn.set("float16",t),$i.set(t,"float16")):pn.set("float16",Uint16Array)}}}),qu,Qu,Db=je(()=>{pd(),qu=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Br(e.type,e.data,r);case"cpu-pinned":return new Br({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Br({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Br({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Br({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Br,pd=je(()=>{Ab(),Fb(),Ob(),Db(),Br=class{constructor(e,r,t){Hu();let s,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=pn.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{let l=pn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(r,BigInt):o=l.from(r)}else if(r instanceof l)o=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=$i.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e}if(a===void 0)a=[o.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");i=a,this.cpuData=o,this.dataLocation="cpu"}let n=qu(i);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=i,this.size=n}static async fromImage(e,r){return Uu(e,r)}static fromTexture(e,r){return Vu(e,r)}static fromGpuBuffer(e,r){return Wu(e,r)}static fromMLTensor(e,r){return Gu(e,r)}static fromPinnedBuffer(e,r,t){return Ku(e,r,t)}toDataURL(e){return Nu(this,e)}toImageData(e){return ju(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Qu(this,e)}}}),ts,Xu=je(()=>{pd(),ts=Br}),ki,hd,rs,Hr,Ju=je(()=>{Ru(),ki=(e,r)=>{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||console.timeStamp(`${e}::ORT::${r}`)},hd=(e,r)=>{var i;let t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||hd("BEGIN",e)},Hr=e=>{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||hd("END",e)}}),Yu,Lb=je(()=>{zu(),Xu(),Ju(),Yu=class ab{constructor(r){this.handler=r}async run(r,t,s){rs();let i={},n={};if(typeof r!="object"||r===null||r instanceof ts||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ts)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let d of t){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,p=Object.getOwnPropertyNames(t);for(let u of this.outputNames)if(p.indexOf(u)!==-1){let h=t[u];(h===null||h instanceof ts)&&(d=!0,o=!1,i[u]=h)}if(d){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of this.inputNames)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(o)for(let d of this.outputNames)i[d]=null;let a=await this.handler.run(r,i,n),l={};for(let d in a)if(Object.hasOwnProperty.call(a,d)){let p=a[d];p instanceof ts?l[d]=p:l[d]=new ts(p.type,p.data,p.dims)}return Hr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){rs();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,u=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-u,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Lu(o),d=await a.createInferenceSessionHandler(n,l);return Hr(),new ab(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),md,zb=je(()=>{Lb(),md=Yu}),Bb=je(()=>{}),Rb=je(()=>{}),Nb=je(()=>{}),jb=je(()=>{}),Zu={};Ci(Zu,{InferenceSession:()=>md,TRACE:()=>ki,TRACE_FUNC_BEGIN:()=>rs,TRACE_FUNC_END:()=>Hr,Tensor:()=>ts,env:()=>Vt,registerBackend:()=>un});var ss=je(()=>{$b(),Ib(),zb(),Xu(),Bb(),Rb(),Ju(),Nb(),jb()}),fd=je(()=>{}),ep={};Ci(ep,{default:()=>tp});var _d,gd,tp,Ub=je(()=>{var e;Aw(),hn(),Ed(),_d="ort-wasm-proxy-worker",gd=((e=globalThis.self)==null?void 0:e.name)===_d,gd&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Sd(s.wasm).then(()=>{zc(s).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:n}=s;Bc(n,i).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:i}=s,n=Fa(i);postMessage({type:t,out:n});break}case"create":{let{model:i,options:n}=s;Rc(i,n).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":Nc(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:n,inputs:o,outputIndices:a,options:l}=s;Uc(i,n,o,a,new Array(a.length).fill(null),l).then(d=>{d.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},Wc([...o,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":Vc(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),tp=gd?null:r=>new Worker(r??Rr,{type:"module",name:_d})}),rp={};Ci(rp,{default:()=>sp});var wd,yd,sp,np,Vb=je(()=>{var e,r;yd=(wd=self.location.href,async function(t={}){var ca;var s,i,n=t,o=new Promise((c,m)=>{s=c,i=m}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",d=l&&((ca=self.name)==null?void 0:ca.startsWith("em-pthread"));n.mountExternalData=(c,m)=>{c.startsWith("./")&&(c=c.substring(2)),(n.Bd||(n.Bd=new Map)).set(c,m)},n.unmountExternalData=()=>{delete n.Bd};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let u=()=>{let c=(b,C,I)=>(...W)=>{let se=Rt,ye=C==null?void 0:C();W=b(...W);let Te=C==null?void 0:C();return ye!==Te&&(b=Te,I(ye),C=I=null),Rt!=se?new Promise((ze,Ye)=>{rn={resolve:ze,reject:Ye}}):W},m=b=>async(...C)=>{var I;try{if(n.Cd)throw Error("Session already started");let W=n.Cd={be:C[0],errors:[]},se=await b(...C);if(n.Cd!==W)throw Error("Session mismatch");(I=n.Dd)==null||I.flush();let ye=W.errors;if(0ze),0n._OrtCreateSession,b=>n._OrtCreateSession=b),n._OrtRun=m(c(n._OrtRun,()=>n._OrtRun,b=>n._OrtRun=b)),n._OrtRunWithBinding=m(c(n._OrtRunWithBinding,()=>n._OrtRunWithBinding,b=>n._OrtRunWithBinding=b)),n._OrtBindInput=c(n._OrtBindInput,()=>n._OrtBindInput,b=>n._OrtBindInput=b),u=void 0};n.jsepInit=(c,m)=>{if(u==null||u(),c==="webgpu"){[n.Dd,n.Rd,n.Vd,n.Hd,n.Ud,n.hc,n.Wd,n.Zd,n.Sd,n.Td,n.Xd]=m;let b=n.Dd;n.jsepRegisterBuffer=(C,I,W,se)=>b.registerBuffer(C,I,W,se),n.jsepGetBuffer=C=>b.getBuffer(C),n.jsepCreateDownloader=(C,I,W)=>b.createDownloader(C,I,W),n.jsepOnCreateSession=C=>{b.onCreateSession(C)},n.jsepOnReleaseSession=C=>{b.onReleaseSession(C)},n.jsepOnRunStart=C=>b.onRunStart(C),n.$d=(C,I)=>{b.upload(C,I)}}else if(c==="webnn"){[n.Dd,n.Yd,n.Id,n.jsepEnsureTensor,n.Jd,n.jsepDownloadTensor]=m,n.jsepReleaseTensorId=n.Id,n.jsepUploadTensor=n.Jd;let b=n.Dd;n.jsepOnRunStart=C=>b.onRunStart(C),n.jsepOnRunEnd=b.onRunEnd.bind(b),n.jsepRegisterMLContext=(C,I)=>{b.registerMLContext(C,I)},n.jsepOnReleaseSession=C=>{b.onReleaseSession(C)},n.jsepCreateMLTensorDownloader=(C,I)=>b.createMLTensorDownloader(C,I),n.jsepRegisterMLTensor=(C,I,W,se)=>b.registerMLTensor(C,I,W,se),n.jsepCreateMLContext=C=>b.createMLContext(C),n.jsepRegisterMLConstant=(C,I,W,se,ye)=>b.registerMLConstant(C,I,W,se,ye,n.Bd),n.jsepRegisterGraphInput=b.registerGraphInput.bind(b),n.jsepIsGraphInput=b.isGraphInput.bind(b),n.jsepCreateTemporaryTensor=b.createTemporaryTensor.bind(b)}};var h,w,_=Object.assign({},n),P=(c,m)=>{throw m},A="";(a||l)&&(l?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),wd&&(A=wd),A=A.startsWith("blob:")?"":A.slice(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(w=c=>{var m=new XMLHttpRequest;return m.open("GET",c,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),h=async c=>{if(ge(c))return new Promise((b,C)=>{var I=new XMLHttpRequest;I.open("GET",c,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?b(I.response):C(I.status)},I.onerror=C,I.send(null)});var m=await fetch(c,{credentials:"same-origin"});if(m.ok)return m.arrayBuffer();throw Error(m.status+" : "+m.url)});var v=console.log.bind(console),y=console.error.bind(console),S=v,x=y;Object.assign(n,_),_=null;var g,M,E,k,B,R,J,q,V,Y,H,Q,ie,le=n.wasmBinary,ae=!1,ge=c=>c.startsWith("file://");function N(){return g.buffer!=k.buffer&&K(),k}function O(){return g.buffer!=k.buffer&&K(),B}function G(){return g.buffer!=k.buffer&&K(),R}function ne(){return g.buffer!=k.buffer&&K(),J}function X(){return g.buffer!=k.buffer&&K(),q}function we(){return g.buffer!=k.buffer&&K(),V}function fe(){return g.buffer!=k.buffer&&K(),Y}function ke(){return g.buffer!=k.buffer&&K(),ie}if(d){let c=function(m){try{var b=m.data,C=b.yd;if(C==="load"){let I=[];self.onmessage=W=>I.push(W),self.startWorker=()=>{postMessage({yd:"loaded"});for(let W of I)c(W);self.onmessage=c};for(let W of b.Od)n[W]&&!n[W].proxy||(n[W]=(...se)=>{postMessage({yd:"callHandler",Nd:W,args:se})},W=="print"&&(S=n[W]),W=="printErr"&&(x=n[W]));g=b.he,K(),He(b.ie)}else if(C==="run"){Fs(b.xd),ri(b.xd,0,0,1,0,0),jt(),Ot(b.xd),Me||(ti(),Me=!0);try{Dr(b.de,b.Fd)}catch(I){if(I!="unwind")throw I}}else b.target!=="setimmediate"&&(C==="checkMailbox"?Me&&Ut():C&&(x(`worker: received unknown command ${C}`),x(b)))}catch(I){throw uo(),I}};var He,Me=!1;x=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({yd:"alert",text:m.join(" "),fe:In()})},self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=c}function K(){var c=g.buffer;n.HEAP8=k=new Int8Array(c),n.HEAP16=R=new Int16Array(c),n.HEAPU8=B=new Uint8Array(c),n.HEAPU16=J=new Uint16Array(c),n.HEAP32=q=new Int32Array(c),n.HEAPU32=V=new Uint32Array(c),n.HEAPF32=Y=new Float32Array(c),n.HEAPF64=ie=new Float64Array(c),n.HEAP64=H=new BigInt64Array(c),n.HEAPU64=Q=new BigUint64Array(c)}function U(){d?startWorker(n):Oe.Bb()}d||(g=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),K());var pe,Pe=0,Ee=null;function Fe(){if(--Pe==0&&Ee){var c=Ee;Ee=null,c()}}function Ie(c){throw x(c="Aborted("+c+")"),ae=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),i(c),c}function Le(){return{a:{Ta:D,Va:Ve,W:Os,la:dt,b:xs,u:Ts,R:Es,Za:Ds,d:mr,pb:et,g:Ur,T:kr,Ga:ps,lb:ms,nb:fs,Ha:Qr,Ea:Ps,wb:qs,Da:Qs,pa:Xs,mb:Js,jb:_s,Fa:Ys,kb:Zs,Ma:Cs,za:Tn,eb:En,cb:Ss,ya:ue,V:F,N:j,db:te,ma:ht,fb:Ct,zb:kt,hb:vr,qb:Yr,ab:xr,Aa:gs,yb:Ot,Ja:Gt,S:Zr,Wa:ws,$:za,H:Ba,E:Na,l:Jr,F:Gi,B:Va,X:Ki,J:Wa,v:Hi,O:Xc,D:Ga,t:qi,A:Ka,z:Kn,w:Ha,r:qa,tb:Qa,ub:Xa,vb:Hn,rb:qn,sb:Yi,bb:Zi,Oa:Jc,La:Yc,y:Ya,ja:Za,Ba:el,Ka:Ja,qa:tl,Ia:rl,ib:Jn,U:js,fa:sl,Sa:nl,gb:il,Qa:to,Pa:ol,Ab:so,Ca:Zn,ob:Ue,aa:no,oa:io,xb:ei,na:oo,$a:Pl,ia:Ol,sa:la,ga:ra,da:kl,ua:Ll,p:xl,e:ul,c:cl,ea:xi,f:pl,n:ml,k:ea,Y:fl,ka:bl,j:Tl,wa:Sl,Ra:da,ca:Al,Ua:Rl,P:$l,K:gl,_:oa,Q:El,Z:aa,x:_l,m:Jo,va:Il,i:dl,h:Yo,ra:Bl,ta:zl,o:hl,q:wl,s:yl,I:Ml,C:ta,L:vl,xa:Cl,_a:sa,G:Fl,Ya:na,ba:Dl,M:Zo,Xa:ia,ha:ao,a:g,Na:Re}}}var Ne={1320978:()=>typeof wasmOffsetConverter<"u",1321035:(c,m,b,C,I)=>{if(n===void 0||!n.Bd)return 1;if((c=zt(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=n.Bd.get(c)))return 2;if(m=Number(m>>>0),b=Number(b>>>0),C=Number(C>>>0),m+b>c.byteLength)return 3;try{let W=c.subarray(m,m+b);switch(I){case 0:O().set(W,C>>>0);break;case 1:n.$d(C,W);break;default:return 4}return 0}catch{return 4}},1321750:(c,m,b)=>{n.Jd(c,O().subarray(m>>>0,m+b>>>0))},1321813:()=>n.Yd(),1321854:c=>{n.Id(c)},1321890:()=>{n.Sd()},1321921:()=>{n.Td()},1321950:()=>{n.Xd()},1321975:c=>n.Rd(c),1322008:c=>n.Vd(c),1322040:(c,m,b)=>{n.Hd(Number(c),Number(m),Number(b),!0)},1322103:(c,m,b)=>{n.Hd(Number(c),Number(m),Number(b))},1322160:c=>{n.hc("Abs",c,void 0)},1322211:c=>{n.hc("Neg",c,void 0)},1322262:c=>{n.hc("Floor",c,void 0)},1322315:c=>{n.hc("Ceil",c,void 0)},1322367:c=>{n.hc("Reciprocal",c,void 0)},1322425:c=>{n.hc("Sqrt",c,void 0)},1322477:c=>{n.hc("Exp",c,void 0)},1322528:c=>{n.hc("Erf",c,void 0)},1322579:c=>{n.hc("Sigmoid",c,void 0)},1322634:(c,m,b)=>{n.hc("HardSigmoid",c,{alpha:m,beta:b})},1322713:c=>{n.hc("Log",c,void 0)},1322764:c=>{n.hc("Sin",c,void 0)},1322815:c=>{n.hc("Cos",c,void 0)},1322866:c=>{n.hc("Tan",c,void 0)},1322917:c=>{n.hc("Asin",c,void 0)},1322969:c=>{n.hc("Acos",c,void 0)},1323021:c=>{n.hc("Atan",c,void 0)},1323073:c=>{n.hc("Sinh",c,void 0)},1323125:c=>{n.hc("Cosh",c,void 0)},1323177:c=>{n.hc("Asinh",c,void 0)},1323230:c=>{n.hc("Acosh",c,void 0)},1323283:c=>{n.hc("Atanh",c,void 0)},1323336:c=>{n.hc("Tanh",c,void 0)},1323388:c=>{n.hc("Not",c,void 0)},1323439:(c,m,b)=>{n.hc("Clip",c,{min:m,max:b})},1323508:c=>{n.hc("Clip",c,void 0)},1323560:(c,m)=>{n.hc("Elu",c,{alpha:m})},1323618:c=>{n.hc("Gelu",c,void 0)},1323670:c=>{n.hc("Relu",c,void 0)},1323722:(c,m)=>{n.hc("LeakyRelu",c,{alpha:m})},1323786:(c,m)=>{n.hc("ThresholdedRelu",c,{alpha:m})},1323856:(c,m)=>{n.hc("Cast",c,{to:m})},1323914:c=>{n.hc("Add",c,void 0)},1323965:c=>{n.hc("Sub",c,void 0)},1324016:c=>{n.hc("Mul",c,void 0)},1324067:c=>{n.hc("Div",c,void 0)},1324118:c=>{n.hc("Pow",c,void 0)},1324169:c=>{n.hc("Equal",c,void 0)},1324222:c=>{n.hc("Greater",c,void 0)},1324277:c=>{n.hc("GreaterOrEqual",c,void 0)},1324339:c=>{n.hc("Less",c,void 0)},1324391:c=>{n.hc("LessOrEqual",c,void 0)},1324450:(c,m,b,C,I)=>{n.hc("ReduceMean",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324625:(c,m,b,C,I)=>{n.hc("ReduceMax",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324799:(c,m,b,C,I)=>{n.hc("ReduceMin",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324973:(c,m,b,C,I)=>{n.hc("ReduceProd",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325148:(c,m,b,C,I)=>{n.hc("ReduceSum",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325322:(c,m,b,C,I)=>{n.hc("ReduceL1",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325495:(c,m,b,C,I)=>{n.hc("ReduceL2",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325668:(c,m,b,C,I)=>{n.hc("ReduceLogSum",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325845:(c,m,b,C,I)=>{n.hc("ReduceSumSquare",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326025:(c,m,b,C,I)=>{n.hc("ReduceLogSumExp",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326205:c=>{n.hc("Where",c,void 0)},1326258:(c,m,b)=>{n.hc("Transpose",c,{perm:m?Array.from(X().subarray(Number(m)>>>0,Number(b)>>>0)):[]})},1326382:(c,m,b,C)=>{n.hc("DepthToSpace",c,{blocksize:m,mode:zt(b),format:C?"NHWC":"NCHW"})},1326515:(c,m,b,C)=>{n.hc("DepthToSpace",c,{blocksize:m,mode:zt(b),format:C?"NHWC":"NCHW"})},1326648:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt,Fr)=>{n.hc("ConvTranspose",c,{format:Te?"NHWC":"NCHW",autoPad:m,dilations:[b],group:C,kernelShape:[I],pads:[W,se],strides:[ye],wIsConst:()=>!!N()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:gt?Array.from(X().subarray(Number(gt)>>>0,Number(Bt)>>>0)):[],activation:zt(Fr)})},1327081:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("ConvTranspose",c,{format:ye?"NHWC":"NCHW",autoPad:m,dilations:Array.from(X().subarray(Number(b)>>>0,2+(Number(b)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(se)>>>0,2+(Number(se)>>>0)>>>0)),wIsConst:()=>!!N()[Te>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[],activation:zt(Bt)})},1327742:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt,Fr)=>{n.hc("ConvTranspose",c,{format:Te?"NHWC":"NCHW",autoPad:m,dilations:[b],group:C,kernelShape:[I],pads:[W,se],strides:[ye],wIsConst:()=>!!N()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:gt?Array.from(X().subarray(Number(gt)>>>0,Number(Bt)>>>0)):[],activation:zt(Fr)})},1328175:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("ConvTranspose",c,{format:ye?"NHWC":"NCHW",autoPad:m,dilations:Array.from(X().subarray(Number(b)>>>0,2+(Number(b)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(se)>>>0,2+(Number(se)>>>0)>>>0)),wIsConst:()=>!!N()[Te>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[],activation:zt(Bt)})},1328836:(c,m)=>{n.hc("GlobalAveragePool",c,{format:m?"NHWC":"NCHW"})},1328927:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("AveragePool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1329406:(c,m)=>{n.hc("GlobalAveragePool",c,{format:m?"NHWC":"NCHW"})},1329497:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("AveragePool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1329976:(c,m)=>{n.hc("GlobalMaxPool",c,{format:m?"NHWC":"NCHW"})},1330063:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("MaxPool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1330538:(c,m)=>{n.hc("GlobalMaxPool",c,{format:m?"NHWC":"NCHW"})},1330625:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("MaxPool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1331100:(c,m,b,C,I)=>{n.hc("Gemm",c,{alpha:m,beta:b,transA:C,transB:I})},1331204:c=>{n.hc("MatMul",c,void 0)},1331258:(c,m,b,C)=>{n.hc("ArgMax",c,{keepDims:!!m,selectLastIndex:!!b,axis:C})},1331366:(c,m,b,C)=>{n.hc("ArgMin",c,{keepDims:!!m,selectLastIndex:!!b,axis:C})},1331474:(c,m)=>{n.hc("Softmax",c,{axis:m})},1331537:(c,m)=>{n.hc("Concat",c,{axis:m})},1331597:(c,m,b,C,I)=>{n.hc("Split",c,{axis:m,numOutputs:b,splitSizes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1331753:c=>{n.hc("Expand",c,void 0)},1331807:(c,m)=>{n.hc("Gather",c,{axis:Number(m)})},1331878:(c,m)=>{n.hc("GatherElements",c,{axis:Number(m)})},1331957:(c,m)=>{n.hc("GatherND",c,{batch_dims:Number(m)})},1332036:(c,m,b,C,I,W,se,ye,Te,ze,Ye)=>{n.hc("Resize",c,{antialias:m,axes:b?Array.from(X().subarray(Number(b)>>>0,Number(C)>>>0)):[],coordinateTransformMode:zt(I),cubicCoeffA:W,excludeOutside:se,extrapolationValue:ye,keepAspectRatioPolicy:zt(Te),mode:zt(ze),nearestMode:zt(Ye)})},1332398:(c,m,b,C,I,W,se)=>{n.hc("Slice",c,{starts:m?Array.from(X().subarray(Number(m)>>>0,Number(b)>>>0)):[],ends:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[],axes:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[]})},1332662:c=>{n.hc("Tile",c,void 0)},1332714:(c,m,b)=>{n.hc("InstanceNormalization",c,{epsilon:m,format:b?"NHWC":"NCHW"})},1332828:(c,m,b)=>{n.hc("InstanceNormalization",c,{epsilon:m,format:b?"NHWC":"NCHW"})},1332942:c=>{n.hc("Range",c,void 0)},1332995:(c,m)=>{n.hc("Einsum",c,{equation:zt(m)})},1333076:(c,m,b,C,I)=>{n.hc("Pad",c,{mode:m,value:b,pads:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1333219:(c,m,b,C,I,W)=>{n.hc("BatchNormalization",c,{epsilon:m,momentum:b,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333388:(c,m,b,C,I,W)=>{n.hc("BatchNormalization",c,{epsilon:m,momentum:b,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333557:(c,m,b)=>{n.hc("CumSum",c,{exclusive:Number(m),reverse:Number(b)})},1333654:(c,m,b)=>{n.hc("DequantizeLinear",c,{axis:m,blockSize:b})},1333744:(c,m,b,C,I)=>{n.hc("GridSample",c,{align_corners:m,mode:zt(b),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1333914:(c,m,b,C,I)=>{n.hc("GridSample",c,{align_corners:m,mode:zt(b),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1334084:(c,m)=>{n.hc("ScatterND",c,{reduction:zt(m)})},1334169:(c,m,b,C,I,W,se,ye,Te)=>{n.hc("Attention",c,{numHeads:m,isUnidirectional:b,maskFilterValue:C,scale:I,doRotary:W,qkvHiddenSizes:se?Array.from(X().subarray(Number(ye)>>>0,Number(ye)+se>>>0)):[],pastPresentShareBuffer:!!Te})},1334441:c=>{n.hc("BiasAdd",c,void 0)},1334496:c=>{n.hc("BiasSplitGelu",c,void 0)},1334557:c=>{n.hc("FastGelu",c,void 0)},1334613:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt,Fr,an)=>{n.hc("Conv",c,{format:ot?"NHWC":"NCHW",auto_pad:m,dilations:b?Array.from(X().subarray(Number(b)>>>0,Number(C)>>>0)):[],group:I,kernel_shape:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],pads:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],strides:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],w_is_const:()=>!!N()[Number(gt)>>>0],activation:zt(Bt),activation_params:Fr?Array.from(fe().subarray(Number(Fr)>>>0,Number(an)>>>0)):[]})},1335197:c=>{n.hc("Gelu",c,void 0)},1335249:(c,m,b,C,I,W,se,ye,Te)=>{n.hc("GroupQueryAttention",c,{numHeads:m,kvNumHeads:b,scale:C,softcap:I,doRotary:W,rotaryInterleaved:se,smoothSoftmax:ye,localWindowSize:Te})},1335466:(c,m,b,C)=>{n.hc("LayerNormalization",c,{axis:m,epsilon:b,simplified:!!C})},1335577:(c,m,b,C)=>{n.hc("LayerNormalization",c,{axis:m,epsilon:b,simplified:!!C})},1335688:(c,m,b,C,I,W)=>{n.hc("MatMulNBits",c,{k:m,n:b,accuracyLevel:C,bits:I,blockSize:W})},1335815:(c,m,b,C,I,W)=>{n.hc("MultiHeadAttention",c,{numHeads:m,isUnidirectional:b,maskFilterValue:C,scale:I,doRotary:W})},1335974:(c,m)=>{n.hc("QuickGelu",c,{alpha:m})},1336038:(c,m,b,C,I)=>{n.hc("RotaryEmbedding",c,{interleaved:!!m,numHeads:b,rotaryEmbeddingDim:C,scale:I})},1336177:(c,m,b)=>{n.hc("SkipLayerNormalization",c,{epsilon:m,simplified:!!b})},1336279:(c,m,b)=>{n.hc("SkipLayerNormalization",c,{epsilon:m,simplified:!!b})},1336381:(c,m,b,C)=>{n.hc("GatherBlockQuantized",c,{gatherAxis:m,quantizeAxis:b,blockSize:C})},1336502:c=>{n.Wd(c)},1336536:(c,m)=>n.Zd(Number(c),Number(m),n.Cd.be,n.Cd.errors)};function Ve(c,m,b){return Vi(async()=>{await n.Ud(Number(c),Number(m),Number(b))})}function D(){return typeof wasmOffsetConverter<"u"}class Z{constructor(m){re(this,"name","ExitStatus");this.message=`Program terminated with exit(${m})`,this.status=m}}var z=c=>{c.terminate(),c.onmessage=()=>{}},ee=[],ce=c=>{Qe.length==0&&(ds(),dr(Qe[0]));var m=Qe.pop();if(!m)return 6;Xe.push(m),xt[c.xd]=m,m.xd=c.xd;var b={yd:"run",de:c.ce,Fd:c.Fd,xd:c.xd};return m.postMessage(b,c.Ld),0},be=0,ve=(c,m,...b)=>{for(var C=2*b.length,I=ft(),W=An(8*C),se=W>>>3,ye=0;ye>>0]=Te)}return c=si(c,0,C,W,m),mt(I),c};function Re(c){if(d)return ve(0,1,c);if(E=c,!(0{if(E=c,d)throw Ae(c),"unwind";Re(c)},Qe=[],Xe=[],ct=[],xt={},nr=c=>{var m=c.xd;delete xt[m],Qe.push(c),Xe.splice(Xe.indexOf(c),1),c.xd=0,po(m)};function jt(){ct.forEach(c=>c())}var dr=c=>new Promise(m=>{c.onmessage=I=>{var W=(I=I.data).yd;if(I.Ed&&I.Ed!=In()){var se=xt[I.Ed];se?se.postMessage(I,I.Ld):x(`Internal error! Worker sent a message "${W}" to target pthread ${I.Ed}, but that thread no longer exists!`)}else W==="checkMailbox"?Ut():W==="spawnThread"?ce(I):W==="cleanupThread"?nr(xt[I.ee]):W==="loaded"?(c.loaded=!0,m(c)):W==="alert"?alert(`Thread ${I.fe}: ${I.text}`):I.target==="setimmediate"?c.postMessage(I):W==="callHandler"?n[I.Nd](...I.args):W&&x(`worker sent an unknown command ${W}`)},c.onerror=I=>{throw x(`worker sent an error! ${I.filename}:${I.lineno}: ${I.message}`),I};var b,C=[];for(b of[])n.propertyIsEnumerable(b)&&C.push(b);c.postMessage({yd:"load",Od:C,he:g,ie:M})});function ds(){var c=new Worker((()=>{let m=URL;return self.location.href>"file:"&&self.location.href<"file;"?new m("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Qe.push(c)}var Fs=c=>{K();var m=we()[c+52>>>2>>>0];c=we()[c+56>>>2>>>0],mo(m,m-c),mt(m)},Dr=(c,m)=>{be=0,c=li(c,m),0>>=0);if(N()[m.wd+12>>>0]==0){var b=1;N()[m.wd+12>>>0]=b}return b=0,N()[m.wd+13>>>0]=b,cs.push(m),oi(c),go(c)}var jr=0,dt=()=>{_t(0,0);var c=cs.pop();fo(c.Gd),jr=0};class qr{constructor(m){this.Gd=m,this.wd=m-24}}function Ur(c){throw jr||(jr=c>>>0),jr}var us=c=>{var m=jr;if(!m)return Us(0),0;var b=new qr(m);we()[b.wd+16>>>2>>>0]=m;var C=we()[b.wd+4>>>2>>>0];if(!C)return Us(0),m;for(var I of c){if(I===0||I===C)break;if(_o(I,C,b.wd+16))return Us(I),m}return Us(C),m};function xs(){return us([])}function Ts(c){return us([c>>>0])}function Es(c,m){return us([c>>>0,m>>>0])}var Ds=()=>{var c=cs.pop();c||Ie("no exception to throw");var m=c.Gd;if(N()[c.wd+13>>>0]==0){cs.push(c);var b=1;N()[c.wd+13>>>0]=b,b=0,N()[c.wd+12>>>0]=b}throw jr=m};function mr(c,m,b){var C=new qr(c>>>=0);throw m>>>=0,b>>>=0,we()[C.wd+16>>>2>>>0]=0,we()[C.wd+4>>>2>>>0]=m,we()[C.wd+8>>>2>>>0]=b,jr=c}function Be(c,m,b,C){return d?ve(2,1,c,m,b,C):et(c,m,b,C)}function et(c,m,b,C){if(c>>>=0,b>>>=0,C>>>=0,p===void 0)return 6;var I=[];return d&&I.length===0?Be(c,m>>>=0,b,C):(c={ce:b,xd:c,Fd:C,Ld:I},d?(c.yd="spawnThread",postMessage(c,I),0):ce(c))}var it=typeof TextDecoder<"u"?new TextDecoder:void 0,rr=(c,m=0,b=NaN)=>{var C=(m>>>=0)+b;for(b=m;c[b]&&!(b>=C);)++b;if(16(I=(240&I)==224?(15&I)<<12|W<<6|se:(7&I)<<18|W<<12|se<<6|63&c[m++])?C+=String.fromCharCode(I):(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I))}}else C+=String.fromCharCode(I)}return C},zt=(c,m)=>(c>>>=0)?rr(O(),c,m):"";function kr(c,m,b){return d?ve(3,1,c,m,b):0}function ps(c,m){if(d)return ve(4,1,c,m)}var hs=c=>{for(var m=0,b=0;b=C?m++:2047>=C?m+=2:55296<=C&&57343>=C?(m+=4,++b):m+=3}return m},Er=(c,m,b)=>{var C=O();if(m>>>=0,0=se&&(se=65536+((1023&se)<<10)|1023&c.charCodeAt(++W)),127>=se){if(m>=b)break;C[m++>>>0]=se}else{if(2047>=se){if(m+1>=b)break;C[m++>>>0]=192|se>>6}else{if(65535>=se){if(m+2>=b)break;C[m++>>>0]=224|se>>12}else{if(m+3>=b)break;C[m++>>>0]=240|se>>18,C[m++>>>0]=128|se>>12&63}C[m++>>>0]=128|se>>6&63}C[m++>>>0]=128|63&se}}C[m>>>0]=0,c=m-I}else c=0;return c};function ms(c,m){if(d)return ve(5,1,c,m)}function fs(c,m,b){if(d)return ve(6,1,c,m,b)}function Qr(c,m,b){return d?ve(7,1,c,m,b):0}function Ps(c,m){if(d)return ve(8,1,c,m)}function qs(c,m,b){if(d)return ve(9,1,c,m,b)}function Qs(c,m,b,C){if(d)return ve(10,1,c,m,b,C)}function Xs(c,m,b,C){if(d)return ve(11,1,c,m,b,C)}function Js(c,m,b,C){if(d)return ve(12,1,c,m,b,C)}function _s(c){if(d)return ve(13,1,c)}function Ys(c,m){if(d)return ve(14,1,c,m)}function Zs(c,m,b){if(d)return ve(15,1,c,m,b)}var en,Lr,Cs=()=>Ie(""),br=c=>{for(var m="";O()[c>>>0];)m+=en[O()[c++>>>0]];return m},Ls={},zs={};function Ir(c,m,b={}){return function(C,I,W={}){var se=I.name;if(!C)throw new Lr(`type "${se}" must have a positive integer typeid pointer`);if(zs.hasOwnProperty(C)){if(W.Pd)return;throw new Lr(`Cannot register type '${se}' twice`)}zs[C]=I,Ls.hasOwnProperty(C)&&(I=Ls[C],delete Ls[C],I.forEach(ye=>ye()))}(c,m,b)}var Xr=(c,m,b)=>{switch(m){case 1:return b?C=>N()[C>>>0]:C=>O()[C>>>0];case 2:return b?C=>G()[C>>>1>>>0]:C=>ne()[C>>>1>>>0];case 4:return b?C=>X()[C>>>2>>>0]:C=>we()[C>>>2>>>0];case 8:return b?C=>H[C>>>3]:C=>Q[C>>>3];default:throw new TypeError(`invalid integer width (${m}): ${c}`)}};function Tn(c,m,b){b>>>=0,Ir(c>>>=0,{name:m=br(m>>>0),fromWireType:C=>C,toWireType:function(C,I){if(typeof I!="bigint"&&typeof I!="number")throw I=I===null?"null":(C=typeof I)=="object"||C==="array"||C==="function"?I.toString():""+I,new TypeError(`Cannot convert "${I}" to ${this.name}`);return typeof I=="number"&&(I=BigInt(I)),I},zd:zr,readValueFromPointer:Xr(m,b,m.indexOf("u")==-1),Ad:null})}var zr=8;function En(c,m,b,C){Ir(c>>>=0,{name:m=br(m>>>0),fromWireType:function(I){return!!I},toWireType:function(I,W){return W?b:C},zd:zr,readValueFromPointer:function(I){return this.fromWireType(O()[I>>>0])},Ad:null})}var Bs=[],Ar=[];function Jr(c){9<(c>>>=0)&&--Ar[c+1]==0&&(Ar[c]=void 0,Bs.push(c))}var cr=c=>{if(!c)throw new Lr("Cannot use deleted val. handle = "+c);return Ar[c]},fr=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Bs.pop()||Ar.length;return Ar[m]=c,Ar[m+1]=1,m}};function Rs(c){return this.fromWireType(we()[c>>>2>>>0])}var Pn={name:"emscripten::val",fromWireType:c=>{var m=cr(c);return Jr(c),m},toWireType:(c,m)=>fr(m),zd:zr,readValueFromPointer:Rs,Ad:null};function Ss(c){return Ir(c>>>0,Pn)}var Cn=(c,m)=>{switch(m){case 4:return function(b){return this.fromWireType(fe()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(ke()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${c}`)}};function ue(c,m,b){b>>>=0,Ir(c>>>=0,{name:m=br(m>>>0),fromWireType:C=>C,toWireType:(C,I)=>I,zd:zr,readValueFromPointer:Cn(m,b),Ad:null})}function F(c,m,b,C,I){if(c>>>=0,b>>>=0,m=br(m>>>0),I===-1&&(I=4294967295),I=ye=>ye,C===0){var W=32-8*b;I=ye=>ye<>>W}var se=m.includes("unsigned")?function(ye,Te){return Te>>>0}:function(ye,Te){return Te};Ir(c,{name:m,fromWireType:I,toWireType:se,zd:zr,readValueFromPointer:Xr(m,b,C!==0),Ad:null})}function j(c,m,b){function C(W){var se=we()[W>>>2>>>0];return W=we()[W+4>>>2>>>0],new I(N().buffer,W,se)}var I=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Ir(c>>>=0,{name:b=br(b>>>0),fromWireType:C,zd:zr,readValueFromPointer:C},{Pd:!0})}function te(c,m){Ir(c>>>=0,{name:m=br(m>>>0),fromWireType:function(b){for(var C,I=we()[b>>>2>>>0],W=b+4,se=W,ye=0;ye<=I;++ye){var Te=W+ye;ye!=I&&O()[Te>>>0]!=0||(se=zt(se,Te-se),C===void 0?C=se:(C+="\0",C+=se),se=Te+1)}return Vr(b),C},toWireType:function(b,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var I=typeof C=="string";if(!(I||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new Lr("Cannot pass non-string to std::string");var W=I?hs(C):C.length,se=on(4+W+1),ye=se+4;if(we()[se>>>2>>>0]=W,I)Er(C,ye,W+1);else if(I)for(I=0;I>>0]=Te}else for(I=0;I>>0]=C[I];return b!==null&&b.push(Vr,se),se},zd:zr,readValueFromPointer:Rs,Ad(b){Vr(b)}})}var de=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,he=(c,m)=>{for(var b=c>>1,C=b+m/2;!(b>=C)&&ne()[b>>>0];)++b;if(32<(b<<=1)-c&&de)return de.decode(O().slice(c,b));for(b="",C=0;!(C>=m/2);++C){var I=G()[c+2*C>>>1>>>0];if(I==0)break;b+=String.fromCharCode(I)}return b},Ce=(c,m,b)=>{if(b??(b=2147483647),2>b)return 0;var C=m;b=(b-=2)<2*c.length?b/2:c.length;for(var I=0;I>>1>>>0]=W,m+=2}return G()[m>>>1>>>0]=0,m-C},We=c=>2*c.length,qe=(c,m)=>{for(var b=0,C="";!(b>=m/4);){var I=X()[c+4*b>>>2>>>0];if(I==0)break;++b,65536<=I?(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I)):C+=String.fromCharCode(I)}return C},Ke=(c,m,b)=>{if(m>>>=0,b??(b=2147483647),4>b)return 0;var C=m;b=C+b-4;for(var I=0;I=W&&(W=65536+((1023&W)<<10)|1023&c.charCodeAt(++I)),X()[m>>>2>>>0]=W,(m+=4)+4>b)break}return X()[m>>>2>>>0]=0,m-C},Ze=c=>{for(var m=0,b=0;b=C&&++b,m+=4}return m};function ht(c,m,b){if(c>>>=0,m>>>=0,b=br(b>>>=0),m===2)var C=he,I=Ce,W=We,se=ye=>ne()[ye>>>1>>>0];else m===4&&(C=qe,I=Ke,W=Ze,se=ye=>we()[ye>>>2>>>0]);Ir(c,{name:b,fromWireType:ye=>{for(var Te,ze=we()[ye>>>2>>>0],Ye=ye+4,ot=0;ot<=ze;++ot){var gt=ye+4+ot*m;ot!=ze&&se(gt)!=0||(Ye=C(Ye,gt-Ye),Te===void 0?Te=Ye:(Te+="\0",Te+=Ye),Ye=gt+m)}return Vr(ye),Te},toWireType:(ye,Te)=>{if(typeof Te!="string")throw new Lr(`Cannot pass non-string to C++ string type ${b}`);var ze=W(Te),Ye=on(4+ze+m);return we()[Ye>>>2>>>0]=ze/m,I(Te,Ye+4,ze+m),ye!==null&&ye.push(Vr,Ye),Ye},zd:zr,readValueFromPointer:Rs,Ad(ye){Vr(ye)}})}function Ct(c,m){Ir(c>>>=0,{Qd:!0,name:m=br(m>>>0),zd:0,fromWireType:()=>{},toWireType:()=>{}})}function kt(c){ri(c>>>0,!l,1,!a,131072,!1),jt()}var Wt=c=>{if(!ae)try{if(c(),!(0>>=0,typeof Atomics.ge=="function"&&(Atomics.ge(X(),c>>>2,c).value.then(Ut),c+=128,Atomics.store(X(),c>>>2,1))}var Ut=()=>{var c=In();c&&(Ot(c),Wt(ho))};function vr(c,m){(c>>>=0)==m>>>0?setTimeout(Ut):d?postMessage({Ed:c,yd:"checkMailbox"}):(c=xt[c])&&c.postMessage({yd:"checkMailbox"})}var _r=[];function Yr(c,m,b,C,I){for(m>>>=0,C/=2,_r.length=C,b=I>>>0>>>3,I=0;I>>0];return(m?Ne[m]:ll[c])(..._r)}var xr=()=>{be=0};function gs(c){c>>>=0,d?postMessage({yd:"cleanupThread",ee:c}):nr(xt[c])}function Gt(c){}var Zt=(c,m)=>{var b=zs[c];if(b===void 0)throw c=co(c),b=br(c),Vr(c),new Lr(`${m} has unknown type ${b}`);return b},gr=(c,m,b)=>{var C=[];return c=c.toWireType(C,b),C.length&&(we()[m>>>2>>>0]=fr(C)),c};function Zr(c,m,b){return m>>>=0,b>>>=0,c=cr(c>>>0),m=Zt(m,"emval::as"),gr(m,b,c)}function ws(c,m){return m>>>=0,c=cr(c>>>0),(m=Zt(m,"emval::as")).toWireType(null,c)}var Ht=c=>{try{c()}catch(m){Ie(m)}},ur=0,Rt=null,Jt=0,qt=[],er={},ir={},tn=0,rn=null,La=[];function Vi(c){return function(m){if(!ae){if(ur===0){var b=!1,C=!1;m((I=0)=>{if(!ae&&(Jt=I,b=!0,C)){ur=2,Ht(()=>Qo(Rt)),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.resume(),I=!1;try{var W=function(){var Te=X()[Rt+8>>>2>>>0];return Te=Oe[ir[Te]],--be,Te()}()}catch(Te){W=Te,I=!0}var se=!1;if(!Rt){var ye=rn;ye&&(rn=null,(I?ye.reject:ye.resolve)(W),se=!0)}if(I&&!se)throw W}}),C=!0,b||(ur=1,Rt=function(){var I=on(65548),W=I+12;we()[I>>>2>>>0]=W,we()[I+4>>>2>>>0]=W+65536,W=qt[0];var se=er[W];return se===void 0&&(se=tn++,er[W]=se,ir[se]=W),W=se,X()[I+8>>>2>>>0]=W,I}(),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.pause(),Ht(()=>qo(Rt)))}else ur===2?(ur=0,Ht(Xo),Vr(Rt),Rt=null,La.forEach(Wt)):Ie(`invalid state: ${ur}`);return Jt}}(m=>{c().then(m)})}function za(c){return c>>>=0,Vi(async()=>{var m=await cr(c);return fr(m)})}var ys=[];function Ba(c,m,b,C){return b>>>=0,C>>>=0,(c=ys[c>>>0])(null,m=cr(m>>>0),b,C)}var Ra={},Sn=c=>{var m=Ra[c];return m===void 0?br(c):m};function Na(c,m,b,C,I){return b>>>=0,C>>>=0,I>>>=0,(c=ys[c>>>0])(m=cr(m>>>0),m[b=Sn(b)],C,I)}var Wi=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Gi(c){return(c>>>=0)==0?fr(Wi()):(c=Sn(c),fr(Wi()[c]))}var ja=c=>{var m=ys.length;return ys.push(c),m},Ua=(c,m)=>{for(var b=Array(c),C=0;C>>2>>>0],"parameter "+C);return b},Gn=(c,m)=>Object.defineProperty(m,"name",{value:c});function Va(c,m,b){var C=(m=Ua(c,m>>>0)).shift();c--;var I=`return function (obj, func, destructorsRef, args) { -`,W=0,se=[];b===0&&se.push("obj");for(var ye=["retType"],Te=[C],ze=0;zeYe.name).join(", ")}) => ${C.name}>`,ja(Gn(b,c))}function Ki(c){return c=Sn(c>>>0),fr(n[c])}function Wa(c,m){return m>>>=0,c=cr(c>>>0),m=cr(m),fr(c[m])}function Hi(c){9<(c>>>=0)&&(Ar[c+1]+=1)}function Xc(){return fr([])}function Ga(c){c=cr(c>>>0);for(var m=Array(c.length),b=0;b>>0))}function Ka(){return fr({})}function Kn(c){for(var m=cr(c>>>=0);m.length;){var b=m.pop();m.pop()(b)}Jr(c)}function Ha(c,m,b){m>>>=0,b>>>=0,c=cr(c>>>0),m=cr(m),b=cr(b),c[m]=b}function qa(c,m){return m>>>=0,c=(c=Zt(c>>>0,"_emval_take_value")).readValueFromPointer(m),fr(c)}function Qa(c,m){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),X()[m>>>2>>>0]=c.getUTCSeconds(),X()[m+4>>>2>>>0]=c.getUTCMinutes(),X()[m+8>>>2>>>0]=c.getUTCHours(),X()[m+12>>>2>>>0]=c.getUTCDate(),X()[m+16>>>2>>>0]=c.getUTCMonth(),X()[m+20>>>2>>>0]=c.getUTCFullYear()-1900,X()[m+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,X()[m+28>>>2>>>0]=c}var Qi=c=>c%4==0&&(c%100!=0||c%400==0),Xi=[0,31,60,91,121,152,182,213,244,274,305,335],Ji=[0,31,59,90,120,151,181,212,243,273,304,334];function Xa(c,m){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),X()[m>>>2>>>0]=c.getSeconds(),X()[m+4>>>2>>>0]=c.getMinutes(),X()[m+8>>>2>>>0]=c.getHours(),X()[m+12>>>2>>>0]=c.getDate(),X()[m+16>>>2>>>0]=c.getMonth(),X()[m+20>>>2>>>0]=c.getFullYear()-1900,X()[m+24>>>2>>>0]=c.getDay();var b=(Qi(c.getFullYear())?Xi:Ji)[c.getMonth()]+c.getDate()-1|0;X()[m+28>>>2>>>0]=b,X()[m+36>>>2>>>0]=-60*c.getTimezoneOffset(),b=new Date(c.getFullYear(),6,1).getTimezoneOffset();var C=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(b!=C&&c.getTimezoneOffset()==Math.min(C,b)),X()[m+32>>>2>>>0]=c}function Hn(c){c>>>=0;var m=new Date(X()[c+20>>>2>>>0]+1900,X()[c+16>>>2>>>0],X()[c+12>>>2>>>0],X()[c+8>>>2>>>0],X()[c+4>>>2>>>0],X()[c>>>2>>>0],0),b=X()[c+32>>>2>>>0],C=m.getTimezoneOffset(),I=new Date(m.getFullYear(),6,1).getTimezoneOffset(),W=new Date(m.getFullYear(),0,1).getTimezoneOffset(),se=Math.min(W,I);return 0>b?X()[c+32>>>2>>>0]=+(I!=W&&se==C):0>>2>>>0]=m.getDay(),b=(Qi(m.getFullYear())?Xi:Ji)[m.getMonth()]+m.getDate()-1|0,X()[c+28>>>2>>>0]=b,X()[c>>>2>>>0]=m.getSeconds(),X()[c+4>>>2>>>0]=m.getMinutes(),X()[c+8>>>2>>>0]=m.getHours(),X()[c+12>>>2>>>0]=m.getDate(),X()[c+16>>>2>>>0]=m.getMonth(),X()[c+20>>>2>>>0]=m.getYear(),c=m.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function qn(c,m,b,C,I,W,se){return d?ve(16,1,c,m,b,C,I,W,se):-52}function Yi(c,m,b,C,I,W){if(d)return ve(17,1,c,m,b,C,I,W)}var Ns={},js=()=>performance.timeOrigin+performance.now();function Zi(c,m){if(d)return ve(18,1,c,m);if(Ns[c]&&(clearTimeout(Ns[c].id),delete Ns[c]),!m)return 0;var b=setTimeout(()=>{delete Ns[c],Wt(()=>ii(c,performance.timeOrigin+performance.now()))},m);return Ns[c]={id:b,ke:m},0}function Jc(c,m,b,C){c>>>=0,m>>>=0,b>>>=0,C>>>=0;var I=new Date().getFullYear(),W=new Date(I,0,1).getTimezoneOffset();I=new Date(I,6,1).getTimezoneOffset();var se=Math.max(W,I);we()[c>>>2>>>0]=60*se,X()[m>>>2>>>0]=+(W!=I),c=(m=ye=>{var Te=Math.abs(ye);return`UTC${0<=ye?"-":"+"}${String(Math.floor(Te/60)).padStart(2,"0")}${String(Te%60).padStart(2,"0")}`})(W),m=m(I),IDate.now();function Yc(c,m,b){return 0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),H[b>>>0>>>3]=BigInt(Math.round(1e6*c)),0):28}var Qn=[],Xn=(c,m)=>{Qn.length=0;for(var b;b=O()[c++>>>0];){var C=b!=105;m+=(C&=b!=112)&&m%8?4:0,Qn.push(b==112?we()[m>>>2>>>0]:b==106?H[m>>>3]:b==105?X()[m>>>2>>>0]:ke()[m>>>3>>>0]),m+=C?8:4}return Qn};function Ya(c,m,b){return c>>>=0,m=Xn(m>>>0,b>>>0),Ne[c](...m)}function Za(c,m,b){return c>>>=0,m=Xn(m>>>0,b>>>0),Ne[c](...m)}var el=()=>{};function tl(c,m){return x(zt(c>>>0,m>>>0))}var rl=()=>{throw be+=1,"unwind"};function Jn(){return 4294901760}var sl=()=>navigator.hardwareConcurrency;function nl(){return Ie("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function il(c){c>>>=0;var m=O().length;if(c<=m||4294901760=b;b*=2){var C=m*(1+.2/b);C=Math.min(C,c+100663296);e:{C=(Math.min(4294901760,65536*Math.ceil(Math.max(c,C)/65536))-g.buffer.byteLength+65535)/65536|0;try{g.grow(C),K();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var sn=()=>(Ie("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),nn={},eo=c=>{c.forEach(m=>{sn()})};function to(){var c=Error().stack.toString().split(` -`);return c[0]=="Error"&&c.shift(),eo(c),nn.Kd=sn(),nn.ae=c,nn.Kd}function ol(c,m,b){if(c>>>=0,m>>>=0,nn.Kd==c)var C=nn.ae;else(C=Error().stack.toString().split(` -`))[0]=="Error"&&C.shift(),eo(C);for(var I=3;C[I]&&sn()!=c;)++I;for(c=0;c>>2>>>0]=sn();return c}var Yn,$n={},ro=()=>{if(!Yn){var c,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in $n)$n[c]===void 0?delete m[c]:m[c]=$n[c];var b=[];for(c in m)b.push(`${c}=${m[c]}`);Yn=b}return Yn};function so(c,m){if(d)return ve(19,1,c,m);c>>>=0,m>>>=0;var b=0;return ro().forEach((C,I)=>{var W=m+b;for(I=we()[c+4*I>>>2>>>0]=W,W=0;W>>0]=C.charCodeAt(W);N()[I>>>0]=0,b+=C.length+1}),0}function Zn(c,m){if(d)return ve(20,1,c,m);c>>>=0,m>>>=0;var b=ro();we()[c>>>2>>>0]=b.length;var C=0;return b.forEach(I=>C+=I.length+1),we()[m>>>2>>>0]=C,0}function no(c){return d?ve(21,1,c):52}function io(c,m,b,C){return d?ve(22,1,c,m,b,C):52}function ei(c,m,b,C){return d?ve(23,1,c,m,b,C):70}var al=[null,[],[]];function oo(c,m,b,C){if(d)return ve(24,1,c,m,b,C);m>>>=0,b>>>=0,C>>>=0;for(var I=0,W=0;W>>2>>>0],ye=we()[m+4>>>2>>>0];m+=8;for(var Te=0;Te>>0],Ye=al[c];ze===0||ze===10?((c===1?S:x)(rr(Ye)),Ye.length=0):Ye.push(ze)}I+=ye}return we()[C>>>2>>>0]=I,0}function ao(c){return c>>>0}d||function(){for(var c=n.numThreads-1;c--;)ds();ee.unshift(()=>{Pe++,function(m){d?m():Promise.all(Qe.map(dr)).then(m)}(()=>Fe())})}();for(var lo=Array(256),kn=0;256>kn;++kn)lo[kn]=String.fromCharCode(kn);en=lo,Lr=n.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},n.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},Ar.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Ar.length/2-5-Bs.length;var Oe,ll=[Re,Ae,Be,kr,ps,ms,fs,Qr,Ps,qs,Qs,Xs,Js,_s,Ys,Zs,qn,Yi,Zi,so,Zn,no,io,ei,oo];(async function(){function c(C,I){return Oe=C.exports,Oe=function(){var W=Oe,se={};for(let[ye,Te]of Object.entries(W))se[ye]=typeof Te=="function"?(...ze)=>{qt.push(ye);try{return Te(...ze)}finally{ae||(qt.pop(),Rt&&ur===1&&qt.length===0&&(ur=0,be+=1,Ht(vi),typeof Fibers<"u"&&Fibers.le()))}}:Te;return se}(),Oe=function(){var W=Oe,se=Te=>ze=>Te(ze)>>>0,ye=Te=>()=>Te()>>>0;return(W=Object.assign({},W)).Cb=se(W.Cb),W.fc=ye(W.fc),W.ic=se(W.ic),W.vc=se(W.vc),W.wc=ye(W.wc),W.Ac=se(W.Ac),W}(),ct.push(Oe.jc),M=I,Fe(),Oe}Pe++;var m=Le();if(n.instantiateWasm)return new Promise(C=>{n.instantiateWasm(m,(I,W)=>{c(I,W),C(I.exports)})});if(d)return new Promise(C=>{He=I=>{var W=new WebAssembly.Instance(I,Le());C(c(W,I))}});pe??(pe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",A):A+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",self.location.href).href);try{var b=await async function(C){var I=pe;if(!le&&typeof WebAssembly.instantiateStreaming=="function"&&!ge(I))try{var W=fetch(I,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(W,C)}catch(se){x(`wasm streaming compile failed: ${se}`),x("falling back to ArrayBuffer instantiation")}return async function(se,ye){try{var Te=await async function(ze){if(!le)try{var Ye=await h(ze);return new Uint8Array(Ye)}catch{}if(ze==pe&&le)ze=new Uint8Array(le);else{if(!w)throw"both async and sync fetching of the wasm failed";ze=w(ze)}return ze}(se);return await WebAssembly.instantiate(Te,ye)}catch(ze){x(`failed to asynchronously prepare wasm: ${ze}`),Ie(ze)}}(I,C)}(m);return c(b.instance,b.module)}catch(C){return i(C),Promise.reject(C)}})();var co=c=>(co=Oe.Cb)(c),ti=()=>(ti=Oe.Db)();n._OrtInit=(c,m)=>(n._OrtInit=Oe.Eb)(c,m),n._OrtGetLastError=(c,m)=>(n._OrtGetLastError=Oe.Fb)(c,m),n._OrtCreateSessionOptions=(c,m,b,C,I,W,se,ye,Te,ze)=>(n._OrtCreateSessionOptions=Oe.Gb)(c,m,b,C,I,W,se,ye,Te,ze),n._OrtAppendExecutionProvider=(c,m)=>(n._OrtAppendExecutionProvider=Oe.Hb)(c,m),n._OrtAddFreeDimensionOverride=(c,m,b)=>(n._OrtAddFreeDimensionOverride=Oe.Ib)(c,m,b),n._OrtAddSessionConfigEntry=(c,m,b)=>(n._OrtAddSessionConfigEntry=Oe.Jb)(c,m,b),n._OrtReleaseSessionOptions=c=>(n._OrtReleaseSessionOptions=Oe.Kb)(c),n._OrtCreateSession=(c,m,b)=>(n._OrtCreateSession=Oe.Lb)(c,m,b),n._OrtReleaseSession=c=>(n._OrtReleaseSession=Oe.Mb)(c),n._OrtGetInputOutputCount=(c,m,b)=>(n._OrtGetInputOutputCount=Oe.Nb)(c,m,b),n._OrtGetInputName=(c,m)=>(n._OrtGetInputName=Oe.Ob)(c,m),n._OrtGetOutputName=(c,m)=>(n._OrtGetOutputName=Oe.Pb)(c,m),n._OrtFree=c=>(n._OrtFree=Oe.Qb)(c),n._OrtCreateTensor=(c,m,b,C,I,W)=>(n._OrtCreateTensor=Oe.Rb)(c,m,b,C,I,W),n._OrtGetTensorData=(c,m,b,C,I)=>(n._OrtGetTensorData=Oe.Sb)(c,m,b,C,I),n._OrtReleaseTensor=c=>(n._OrtReleaseTensor=Oe.Tb)(c),n._OrtCreateRunOptions=(c,m,b,C)=>(n._OrtCreateRunOptions=Oe.Ub)(c,m,b,C),n._OrtAddRunConfigEntry=(c,m,b)=>(n._OrtAddRunConfigEntry=Oe.Vb)(c,m,b),n._OrtReleaseRunOptions=c=>(n._OrtReleaseRunOptions=Oe.Wb)(c),n._OrtCreateBinding=c=>(n._OrtCreateBinding=Oe.Xb)(c),n._OrtBindInput=(c,m,b)=>(n._OrtBindInput=Oe.Yb)(c,m,b),n._OrtBindOutput=(c,m,b,C)=>(n._OrtBindOutput=Oe.Zb)(c,m,b,C),n._OrtClearBoundOutputs=c=>(n._OrtClearBoundOutputs=Oe._b)(c),n._OrtReleaseBinding=c=>(n._OrtReleaseBinding=Oe.$b)(c),n._OrtRunWithBinding=(c,m,b,C,I)=>(n._OrtRunWithBinding=Oe.ac)(c,m,b,C,I),n._OrtRun=(c,m,b,C,I,W,se,ye)=>(n._OrtRun=Oe.bc)(c,m,b,C,I,W,se,ye),n._OrtEndProfiling=c=>(n._OrtEndProfiling=Oe.cc)(c),n._JsepOutput=(c,m,b)=>(n._JsepOutput=Oe.dc)(c,m,b),n._JsepGetNodeName=c=>(n._JsepGetNodeName=Oe.ec)(c);var In=()=>(In=Oe.fc)(),Vr=n._free=c=>(Vr=n._free=Oe.gc)(c),on=n._malloc=c=>(on=n._malloc=Oe.ic)(c),ri=(c,m,b,C,I,W)=>(ri=Oe.kc)(c,m,b,C,I,W),uo=()=>(uo=Oe.lc)(),si=(c,m,b,C,I)=>(si=Oe.mc)(c,m,b,C,I),po=c=>(po=Oe.nc)(c),ni=c=>(ni=Oe.oc)(c),ii=(c,m)=>(ii=Oe.pc)(c,m),ho=()=>(ho=Oe.qc)(),_t=(c,m)=>(_t=Oe.rc)(c,m),Us=c=>(Us=Oe.sc)(c),mo=(c,m)=>(mo=Oe.tc)(c,m),mt=c=>(mt=Oe.uc)(c),An=c=>(An=Oe.vc)(c),ft=()=>(ft=Oe.wc)(),fo=c=>(fo=Oe.xc)(c),oi=c=>(oi=Oe.yc)(c),_o=(c,m,b)=>(_o=Oe.zc)(c,m,b),go=c=>(go=Oe.Ac)(c),ai=n.dynCall_iii=(c,m,b)=>(ai=n.dynCall_iii=Oe.Bc)(c,m,b),wo=n.dynCall_vi=(c,m)=>(wo=n.dynCall_vi=Oe.Cc)(c,m),li=n.dynCall_ii=(c,m)=>(li=n.dynCall_ii=Oe.Dc)(c,m),di=n.dynCall_vii=(c,m,b)=>(di=n.dynCall_vii=Oe.Ec)(c,m,b),yo=n.dynCall_iiii=(c,m,b,C)=>(yo=n.dynCall_iiii=Oe.Fc)(c,m,b,C),Mo=n.dynCall_viii=(c,m,b,C)=>(Mo=n.dynCall_viii=Oe.Gc)(c,m,b,C),ci=n.dynCall_iiiii=(c,m,b,C,I)=>(ci=n.dynCall_iiiii=Oe.Hc)(c,m,b,C,I),bo=n.dynCall_viiii=(c,m,b,C,I)=>(bo=n.dynCall_viiii=Oe.Ic)(c,m,b,C,I),vo=n.dynCall_viiiiii=(c,m,b,C,I,W,se)=>(vo=n.dynCall_viiiiii=Oe.Jc)(c,m,b,C,I,W,se),ui=n.dynCall_viiiiiii=(c,m,b,C,I,W,se,ye)=>(ui=n.dynCall_viiiiiii=Oe.Kc)(c,m,b,C,I,W,se,ye),xo=n.dynCall_ji=(c,m)=>(xo=n.dynCall_ji=Oe.Lc)(c,m),To=n.dynCall_v=c=>(To=n.dynCall_v=Oe.Mc)(c),pi=n.dynCall_viiiii=(c,m,b,C,I,W)=>(pi=n.dynCall_viiiii=Oe.Nc)(c,m,b,C,I,W),Eo=n.dynCall_i=c=>(Eo=n.dynCall_i=Oe.Oc)(c),Po=n.dynCall_fii=(c,m,b)=>(Po=n.dynCall_fii=Oe.Pc)(c,m,b),hi=n.dynCall_viiiiiiii=(c,m,b,C,I,W,se,ye,Te)=>(hi=n.dynCall_viiiiiiii=Oe.Qc)(c,m,b,C,I,W,se,ye,Te),Co=n.dynCall_viiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye)=>(Co=n.dynCall_viiiiiiiiii=Oe.Rc)(c,m,b,C,I,W,se,ye,Te,ze,Ye),So=n.dynCall_jiii=(c,m,b,C)=>(So=n.dynCall_jiii=Oe.Sc)(c,m,b,C),mi=n.dynCall_dii=(c,m,b)=>(mi=n.dynCall_dii=Oe.Tc)(c,m,b),$o=n.dynCall_viiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze)=>($o=n.dynCall_viiiiiiiii=Oe.Uc)(c,m,b,C,I,W,se,ye,Te,ze),ko=n.dynCall_viiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot)=>(ko=n.dynCall_viiiiiiiiiii=Oe.Vc)(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot),Io=n.dynCall_iiiiii=(c,m,b,C,I,W)=>(Io=n.dynCall_iiiiii=Oe.Wc)(c,m,b,C,I,W),Ao=n.dynCall_iij=(c,m,b)=>(Ao=n.dynCall_iij=Oe.Xc)(c,m,b),fi=n.dynCall_iiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze)=>(fi=n.dynCall_iiiiiiiiii=Oe.Yc)(c,m,b,C,I,W,se,ye,Te,ze),Fo=n.dynCall_iiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye)=>(Fo=n.dynCall_iiiiiiiiiii=Oe.Zc)(c,m,b,C,I,W,se,ye,Te,ze,Ye),Oo=n.dynCall_vij=(c,m,b)=>(Oo=n.dynCall_vij=Oe._c)(c,m,b),_i=n.dynCall_iiif=(c,m,b,C)=>(_i=n.dynCall_iiif=Oe.$c)(c,m,b,C),Do=n.dynCall_iiij=(c,m,b,C)=>(Do=n.dynCall_iiij=Oe.ad)(c,m,b,C),Lo=n.dynCall_fiii=(c,m,b,C)=>(Lo=n.dynCall_fiii=Oe.bd)(c,m,b,C),gi=n.dynCall_viiiiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>(gi=n.dynCall_viiiiiiiiiiiii=Oe.cd)(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt),zo=n.dynCall_vjiii=(c,m,b,C,I)=>(zo=n.dynCall_vjiii=Oe.dd)(c,m,b,C,I),Bo=n.dynCall_vif=(c,m,b)=>(Bo=n.dynCall_vif=Oe.ed)(c,m,b),wi=n.dynCall_iiiiiii=(c,m,b,C,I,W,se)=>(wi=n.dynCall_iiiiiii=Oe.fd)(c,m,b,C,I,W,se),Ro=n.dynCall_iiiij=(c,m,b,C,I)=>(Ro=n.dynCall_iiiij=Oe.gd)(c,m,b,C,I),No=n.dynCall_iiiiiiii=(c,m,b,C,I,W,se,ye)=>(No=n.dynCall_iiiiiiii=Oe.hd)(c,m,b,C,I,W,se,ye),yi=n.dynCall_viiiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt)=>(yi=n.dynCall_viiiiiiiiiiii=Oe.id)(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt),jo=n.dynCall_diii=(c,m,b,C)=>(jo=n.dynCall_diii=Oe.jd)(c,m,b,C),Uo=n.dynCall_jiiii=(c,m,b,C,I)=>(Uo=n.dynCall_jiiii=Oe.kd)(c,m,b,C,I),Mi=n.dynCall_viiij=(c,m,b,C,I)=>(Mi=n.dynCall_viiij=Oe.ld)(c,m,b,C,I),Vo=n.dynCall_fiiii=(c,m,b,C,I)=>(Vo=n.dynCall_fiiii=Oe.md)(c,m,b,C,I),Wo=n.dynCall_viiif=(c,m,b,C,I)=>(Wo=n.dynCall_viiif=Oe.nd)(c,m,b,C,I),bi=n.dynCall_diiii=(c,m,b,C,I)=>(bi=n.dynCall_diiii=Oe.od)(c,m,b,C,I),Go=n.dynCall_viiid=(c,m,b,C,I)=>(Go=n.dynCall_viiid=Oe.pd)(c,m,b,C,I),Ko=n.dynCall_iiiijii=(c,m,b,C,I,W,se)=>(Ko=n.dynCall_iiiijii=Oe.qd)(c,m,b,C,I,W,se),Ho=n.dynCall_iiiiiij=(c,m,b,C,I,W,se)=>(Ho=n.dynCall_iiiiiij=Oe.rd)(c,m,b,C,I,W,se),qo=c=>(qo=Oe.sd)(c),vi=()=>(vi=Oe.td)(),Qo=c=>(Qo=Oe.ud)(c),Xo=()=>(Xo=Oe.vd)();function dl(c,m,b){var C=ft();try{di(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function cl(c,m,b){var C=ft();try{return ai(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function Jo(c,m){var b=ft();try{wo(c,m)}catch(C){if(mt(b),C!==C+0)throw C;_t(1,0)}}function ul(c,m){var b=ft();try{return li(c,m)}catch(C){if(mt(b),C!==C+0)throw C;_t(1,0)}}function pl(c,m,b,C){var I=ft();try{return yo(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;_t(1,0)}}function hl(c,m,b,C,I){var W=ft();try{bo(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function ml(c,m,b,C,I){var W=ft();try{return ci(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function Yo(c,m,b,C){var I=ft();try{Mo(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;_t(1,0)}}function fl(c,m,b,C,I,W,se){var ye=ft();try{return wi(c,m,b,C,I,W,se)}catch(Te){if(mt(ye),Te!==Te+0)throw Te;_t(1,0)}}function _l(c){var m=ft();try{To(c)}catch(b){if(mt(m),b!==b+0)throw b;_t(1,0)}}function gl(c,m,b){var C=ft();try{return Ao(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function wl(c,m,b,C,I,W){var se=ft();try{pi(c,m,b,C,I,W)}catch(ye){if(mt(se),ye!==ye+0)throw ye;_t(1,0)}}function Zo(c,m,b){var C=ft();try{Oo(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function yl(c,m,b,C,I,W,se){var ye=ft();try{vo(c,m,b,C,I,W,se)}catch(Te){if(mt(ye),Te!==Te+0)throw Te;_t(1,0)}}function Ml(c,m,b,C,I,W,se,ye){var Te=ft();try{ui(c,m,b,C,I,W,se,ye)}catch(ze){if(mt(Te),ze!==ze+0)throw ze;_t(1,0)}}function ea(c,m,b,C,I,W){var se=ft();try{return Io(c,m,b,C,I,W)}catch(ye){if(mt(se),ye!==ye+0)throw ye;_t(1,0)}}function bl(c,m,b,C,I,W,se,ye){var Te=ft();try{return No(c,m,b,C,I,W,se,ye)}catch(ze){if(mt(Te),ze!==ze+0)throw ze;_t(1,0)}}function vl(c,m,b,C,I,W,se,ye,Te,ze){var Ye=ft();try{$o(c,m,b,C,I,W,se,ye,Te,ze)}catch(ot){if(mt(Ye),ot!==ot+0)throw ot;_t(1,0)}}function ta(c,m,b,C,I,W,se,ye,Te){var ze=ft();try{hi(c,m,b,C,I,W,se,ye,Te)}catch(Ye){if(mt(ze),Ye!==Ye+0)throw Ye;_t(1,0)}}function xl(c){var m=ft();try{return Eo(c)}catch(b){if(mt(m),b!==b+0)throw b;_t(1,0)}}function Tl(c,m,b,C,I,W,se,ye,Te,ze){var Ye=ft();try{return fi(c,m,b,C,I,W,se,ye,Te,ze)}catch(ot){if(mt(Ye),ot!==ot+0)throw ot;_t(1,0)}}function ra(c,m,b){var C=ft();try{return Po(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function El(c,m,b,C){var I=ft();try{return So(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;return _t(1,0),0n}}function Pl(c,m,b){var C=ft();try{return mi(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function sa(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot){var gt=ft();try{ko(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot)}catch(Bt){if(mt(gt),Bt!==Bt+0)throw Bt;_t(1,0)}}function Cl(c,m,b,C,I,W,se,ye,Te,ze,Ye){var ot=ft();try{Co(c,m,b,C,I,W,se,ye,Te,ze,Ye)}catch(gt){if(mt(ot),gt!==gt+0)throw gt;_t(1,0)}}function Sl(c,m,b,C,I,W,se,ye,Te,ze,Ye){var ot=ft();try{return Fo(c,m,b,C,I,W,se,ye,Te,ze,Ye)}catch(gt){if(mt(ot),gt!==gt+0)throw gt;_t(1,0)}}function xi(c,m,b,C){var I=ft();try{return _i(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;_t(1,0)}}function $l(c,m,b,C){var I=ft();try{return Do(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;_t(1,0)}}function kl(c,m,b,C){var I=ft();try{return Lo(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;_t(1,0)}}function na(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt){var Fr=ft();try{gi(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)}catch(an){if(mt(Fr),an!==an+0)throw an;_t(1,0)}}function ia(c,m,b,C,I){var W=ft();try{zo(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function Il(c,m,b){var C=ft();try{Bo(c,m,b)}catch(I){if(mt(C),I!==I+0)throw I;_t(1,0)}}function oa(c,m){var b=ft();try{return xo(c,m)}catch(C){if(mt(b),C!==C+0)throw C;return _t(1,0),0n}}function Al(c,m,b,C,I){var W=ft();try{return Ro(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function Fl(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt){var Bt=ft();try{yi(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt)}catch(Fr){if(mt(Bt),Fr!==Fr+0)throw Fr;_t(1,0)}}function Ol(c,m,b,C){var I=ft();try{return jo(c,m,b,C)}catch(W){if(mt(I),W!==W+0)throw W;_t(1,0)}}function aa(c,m,b,C,I){var W=ft();try{return Uo(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;return _t(1,0),0n}}function Dl(c,m,b,C,I){var W=ft();try{Mi(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function Ll(c,m,b,C,I){var W=ft();try{return Vo(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function zl(c,m,b,C,I){var W=ft();try{Wo(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function la(c,m,b,C,I){var W=ft();try{return bi(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function Bl(c,m,b,C,I){var W=ft();try{Go(c,m,b,C,I)}catch(se){if(mt(W),se!==se+0)throw se;_t(1,0)}}function Rl(c,m,b,C,I,W,se){var ye=ft();try{return Ko(c,m,b,C,I,W,se)}catch(Te){if(mt(ye),Te!==Te+0)throw Te;_t(1,0)}}function da(c,m,b,C,I,W,se){var ye=ft();try{return Ho(c,m,b,C,I,W,se)}catch(Te){if(mt(ye),Te!==Te+0)throw Te;_t(1,0)}}return n.stackSave=()=>ft(),n.stackRestore=c=>mt(c),n.stackAlloc=c=>An(c),n.setValue=function(c,m,b="i8"){switch(b.endsWith("*")&&(b="*"),b){case"i1":case"i8":N()[c>>>0]=m;break;case"i16":G()[c>>>1>>>0]=m;break;case"i32":X()[c>>>2>>>0]=m;break;case"i64":H[c>>>3]=BigInt(m);break;case"float":fe()[c>>>2>>>0]=m;break;case"double":ke()[c>>>3>>>0]=m;break;case"*":we()[c>>>2>>>0]=m;break;default:Ie(`invalid type for setValue: ${b}`)}},n.getValue=function(c,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return N()[c>>>0];case"i16":return G()[c>>>1>>>0];case"i32":return X()[c>>>2>>>0];case"i64":return H[c>>>3];case"float":return fe()[c>>>2>>>0];case"double":return ke()[c>>>3>>>0];case"*":return we()[c>>>2>>>0];default:Ie(`invalid type for getValue: ${m}`)}},n.UTF8ToString=zt,n.stringToUTF8=Er,n.lengthBytesUTF8=hs,function c(){if(0{fd(),Md=typeof location>"u"?void 0:location.origin,bd=self.location.href>"file:"&&self.location.href<"file;",ip=()=>{{if(bd){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Md).href}return self.location.href}},Rr=ip(),op=()=>{if(Rr&&!Rr.startsWith("blob:"))return Rr.substring(0,Rr.lastIndexOf("/")+1)},_a=(e,r)=>{try{let t=r??Rr;return(t?new URL(e,t):new URL(e)).origin===Md}catch{return!1}},ap=(e,r)=>{let t=r??Rr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},lp=(e,r)=>`${r??"./"}${e}`,vd=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},dp=async e=>(await import(e)).default,xd=(Ub(),ma(ep)).default,cp=async()=>{if(!Rr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(_a(Rr))return[void 0,xd()];let e=await vd(Rr);return[e,xd(e)]},Td=(Vb(),ma(rp)).default,up=async(e,r,t)=>{if(!e&&!r&&Td&&Rr&&_a(Rr))return[void 0,Td];{let s="ort-wasm-simd-threaded.jsep.mjs",i=e??ap(s,r),n=t&&i&&!_a(i,r),o=n?await vd(i):i??lp(s,r);return[n?o:void 0,await dp(o)]}}}),Pd,ga,Ii,Cd,pp,hp,Sd,ar,hn=je(()=>{Ed(),ga=!1,Ii=!1,Cd=!1,pp=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},hp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Sd=async e=>{if(ga)return Promise.resolve();if(Ii)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Cd)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ii=!0;let r=e.initTimeout,t=e.numThreads;if(!hp())throw new Error("WebAssembly SIMD is not supported in the current environment.");let s=pp();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let i=e.wasmPaths,n=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,a=(o==null?void 0:o.href)??o,l=i==null?void 0:i.wasm,d=(l==null?void 0:l.href)??l,p=e.wasmBinary,[u,h]=await up(a,n,t>1),w=!1,_=[];if(r>0&&_.push(new Promise(P=>{setTimeout(()=>{w=!0,P()},r)})),_.push(new Promise((P,A)=>{let v={numThreads:t};if(p)v.wasmBinary=p;else if(d||n)v.locateFile=y=>d??n+y;else if(a&&a.indexOf("blob:")!==0)v.locateFile=y=>new URL(y,a).href;else if(u){let y=op();y&&(v.locateFile=S=>y+S)}h(v).then(y=>{Ii=!1,ga=!0,Pd=y,P(),u&&URL.revokeObjectURL(u)},y=>{Ii=!1,Cd=!0,A(y)})})),await Promise.race(_),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},ar=()=>{if(ga&&Pd)return Pd;throw new Error("WebAssembly is not initialized yet.")}}),Mr,wa,At,$d=je(()=>{hn(),Mr=(e,r)=>{let t=ar(),s=t.lengthBytesUTF8(e)+1,i=t._malloc(s);return t.stringToUTF8(e,i,s),r.push(i),i},wa=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([i,n])=>{let o=r?r+i:i;if(typeof n=="object")wa(n,o+".",t,s);else if(typeof n=="string"||typeof n=="number")s(o,n.toString());else if(typeof n=="boolean")s(o,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},At=e=>{let r=ar(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetLastError(i,i+s);let n=Number(r.getValue(i,s===4?"i32":"i64")),o=r.getValue(i+s,"*"),a=o?r.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),mp,Wb=je(()=>{hn(),$d(),mp=e=>{let r=ar(),t=0,s=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=Mr(e.tag,s)),t=r._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&wa(e.extra,"",new WeakSet,(o,a)=>{let l=Mr(o,s),d=Mr(a,s);r._OrtAddRunConfigEntry(t,l,d)!==0&&At(`Can't set a run config entry: ${o} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(o=>r._free(o)),n}}}),fp,_p,gp,wp,yp,Gb=je(()=>{hn(),$d(),fp=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},_p=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},gp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},wp=(e,r,t)=>{for(let s of r){let i=typeof s=="string"?s:s.name;switch(i){case"webnn":if(i="WEBNN",typeof s!="string"){let o=s==null?void 0:s.deviceType;if(o){let a=Mr("deviceType",t),l=Mr(o,t);ar()._OrtAddSessionConfigEntry(e,a,l)!==0&&At(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof s!="string"){let o=s;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let a=Mr("preferredLayout",t),l=Mr(o.preferredLayout,t);ar()._OrtAddSessionConfigEntry(e,a,l)!==0&&At(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let n=Mr(i,t);ar()._OrtAppendExecutionProvider(e,n)!==0&&At(`Can't append execution provider: ${i}.`)}},yp=e=>{let r=ar(),t=0,s=[],i=e||{};gp(i);try{let n=fp(i.graphOptimizationLevel??"all"),o=_p(i.executionMode??"sequential"),a=typeof i.logId=="string"?Mr(i.logId,s):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let d=i.logVerbosityLevel??0;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log verbosity level is not valid: ${d}`);let p=typeof i.optimizedModelFilePath=="string"?Mr(i.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,a,l,d,p),t===0&&At("Can't create session options."),i.executionProviders&&wp(t,i.executionProviders,s),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let u=Mr("enableGraphCapture",s),h=Mr(i.enableGraphCapture.toString(),s);r._OrtAddSessionConfigEntry(t,u,h)!==0&&At(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[u,h]of Object.entries(i.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let w=Mr(u,s);r._OrtAddFreeDimensionOverride(t,w,h)!==0&&At(`Can't set a free dimension override: ${u} - ${h}.`)}return i.extra!==void 0&&wa(i.extra,"",new WeakSet,(u,h)=>{let w=Mr(u,s),_=Mr(h,s);r._OrtAddSessionConfigEntry(t,w,_)!==0&&At(`Can't set a session config entry: ${u} - ${h}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(o=>r._free(o)),n}}}),Rn,mn,fn,kd,ya,Id,Ad,Fd,pt=je(()=>{Rn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},mn=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},fn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((i,n)=>i*n,1);return t>0?Math.ceil(s*t):void 0},kd=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},ya=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Id=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ad=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Fd=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Od,Mp=je(()=>{fd(),Od=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let o=0;for(;;){let{done:a,value:l}=await i.read();if(a)break;let d=l.byteLength;new Uint8Array(n,o,d).set(l),o+=d}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),bp,vp,xp,Tp,Dd,Ep,St,ks=je(()=>{pt(),bp=["V","I","W","E","F"],vp=(e,r)=>{console.log(`[${bp[e]},${new Date().toISOString()}]${r}`)},Dd=(e,r)=>{xp=e,Tp=r},Ep=(e,r)=>{let t=ya(e),s=ya(xp);t>=s&&vp(t,typeof r=="function"?r():r)},St=(...e)=>{Tp&&Ep(...e)}}),Ld,Pp=je(()=>{pt(),Ld=(e,r)=>new(kd(r))(e)}),zd=je(()=>{}),Bd,Ma,ba,Cp,Sp,Rd,Nd,$p,kp,Kb=je(()=>{ks(),zd(),Bd=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ma=[],ba=e=>Math.ceil(Number(e)/16)*16,Cp=e=>{for(let r=0;rSp++,Nd=async(e,r,t,s)=>{let i=ba(t),n=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(r,0,n,0,i),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},$p=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of Bd)Ma.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,i=r.byteLength,n=ba(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,i)),a.unmap();let d=this.backend.device.createCommandEncoder();d.copyBufferToBuffer(a,0,o.gpuData.buffer,0,n),this.backend.device.queue.submit([d.finish()]),a.destroy(),St("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=ba(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,i)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. - Please use the previous external buffer!`)}else s=Rd();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),St("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Cp(e),s,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||n){let a=(i?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let o={id:Rd(),type:0,buffer:s};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),St("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return St("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await Nd(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=Bd.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(St("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},kp=(...e)=>new $p(...e)}),Ip,Dt,Yt=je(()=>{Ip=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Dt=e=>new Ip(e)}),Ap,Nn,xe,va,Fp,Op,Dp,yt=je(()=>{Ap=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Nn=class{static calcShape(e,r,t=!1){let s=e.length,i=r.length;if(s===0)return r;if(i===0)return e;let n=Math.max(e.length,r.length),o=new Array(n);if(t){if(s<2||i<2)return;let a=Ap.calcMatMulShape([e[s-2],e[s-1]],[r[i-2],r[i-1]]);if(a===void 0)return;[o[n-2],o[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],d=i-a<0?1:r[i-a];if(l!==d&&l>1&&d>1)return;let p=Math.max(l,d);if(l&&d)o[n-a]=Math.max(l,d);else{if(p>1)return;o[n-a]=0}}return o}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let i=1;i<=t;i++)if(e[t-i]!==1&&e[t-i]!==r[s-i])return!1;return!0}},xe=class id{static size(r){return id.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let i=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){i[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");i[n]=1,t/=r[n],n--}for(n--;n>=0;n--)i[n]=r[n];return i}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return id.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return id.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let i=1;for(let n=t;n=0;--i)s[i]=s[i+1]*r[i+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((i,n)=>i+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,i)=>s===t[i])}},va=class pa{static adjustPoolAttributes(r,t,s,i,n,o){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||o[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,i,n,o,a){if(a){if(n.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{pt(),yt(),jn=64,xa=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},lr=(e,r=1)=>{let t=xa(e,r);return typeof t=="string"?t:t[0]},Tr=(e,r=1)=>{let t=xa(e,r);return typeof t=="string"?t:t[1]},nt=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:xe.computeStrides(t)})}),r},Xt=e=>e%4===0?4:e%2===0?2:1,jd=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Un=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ws=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,rt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,Ai=(e,r,t,s,i)=>{let n=typeof t=="number",o=n?t:t.length,a=[...new Array(o).keys()],l=o<2?"u32":o<=4?`vec${o}`:`array`,d=xa(r,i),p=typeof d=="string"?d:d[1],u=typeof d=="string"?d:d[0],h={indices:l,value:p,storage:u,tensor:r},w=N=>typeof N=="string"?N:`${N}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},P=n?"uniforms.":"",A=`${P}${e}_shape`,v=`${P}${e}_strides`,y="";for(let N=0;Ntypeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ue=(e,r)=>()=>(e&&(r=e(e=0)),r),Ci=(e,r)=>{for(var t in r)cd(e,t,{get:r[t],enumerable:!0})},Rb=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Lb(r))!zb.call(e,i)&&i!==t&&cd(e,i,{get:()=>r[i],enumerable:!(s=Db(r,i))||s.enumerable});return e},ma=e=>Rb(cd({},"__esModule",{value:!0}),e),Si,Vs,un,Lu,zu,Bu=Ue(()=>{Si=new Map,Vs=[],un=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Si.get(e);if(s===void 0)Si.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let i=Vs.indexOf(e);i!==-1&&Vs.splice(i,1);for(let n=0;n{let r=Si.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},zu=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Vs:t,i,n=[],o=new Set;for(let l of s){let d=await Lu(l);typeof d=="string"?n.push({name:l,err:d}):(i||(i=d),i===d&&o.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:d}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);let a=r.filter(l=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,d)=>d==="executionProviders"?a:Reflect.get(l,d)})]}}),Nb=Ue(()=>{Bu()}),Ru,jb=Ue(()=>{Ru="1.22.0-dev.20250306-aafa8d170a"}),ud,Kr,Nu=Ue(()=>{jb(),ud="warning",Kr={wasm:{},webgl:{},webgpu:{},versions:{common:Ru},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);ud=e}},get logLevel(){return ud}},Object.defineProperty(Kr,"logLevel",{enumerable:!0})}),Vt,Ub=Ue(()=>{Nu(),Vt=Kr}),ju,Uu,Vb=Ue(()=>{ju=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);let o=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,d;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));let p=n*i,u=0,h=p,w=p*2,f=-1;o==="RGBA"?(u=0,h=p,w=p*2,f=p*3):o==="RGB"?(u=0,h=p,w=p*2):o==="RBG"&&(u=0,w=p,h=p*2);for(let P=0;P{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let u=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,w=0,f=1,P=2,A=3,b=0,y=u,$=u*2,T=-1;a==="RGBA"?(b=0,y=u,$=u*2,T=u*3):a==="RGB"?(b=0,y=u,$=u*2):a==="RBG"&&(b=0,$=u,y=u*2),s=t.createImageData(i,n);for(let g=0;g{hd(),_a=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,i=r.norm??{mean:255,bias:0},n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",d=t*s,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,h=0,w=1,f=2,P=3,A=0,b=d,y=d*2,$=-1;a==="RGB"&&(u=3,h=0,w=1,f=2,P=-1),l==="RGBA"?$=d*3:l==="RBG"?(A=0,y=d,b=d*2):l==="BGR"&&(y=0,b=d,A=d*2);for(let T=0;T{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",o,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let u=d(p);if(u!=null){let h=e.height,w=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,w=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=w}else a.tensorFormat="RGBA",a.height=h,a.width=w;u.drawImage(e,0,0),o=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=u,r!==void 0){let h=l();h.width=u,h.height=p;let w=d(h);if(w!=null)w.putImageData(e,0,0),o=w.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let u=d(p);if(u!=null){let h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),o=u.getImageData(0,0,w,h).data,a.height=h,a.width=w,_a(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,u)=>{let h=l(),w=d(h);if(!e||!w)return u();let f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{h.width=f.width,h.height=f.height,w.drawImage(f,0,0,h.width,h.height);let P=w.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(_a(P.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return _a(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Wu=(e,r)=>{let{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Br({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},Gu=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Br({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},Ku=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Br({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},Hu=(e,r,t)=>new Br({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),pn,$i,pd,qu,Gb=Ue(()=>{pn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),$i=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),pd=!1,qu=()=>{if(!pd){pd=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(pn.set("int64",BigInt64Array),$i.set(BigInt64Array,"int64")),r&&(pn.set("uint64",BigUint64Array),$i.set(BigUint64Array,"uint64")),s?(pn.set("float16",t),$i.set(t,"float16")):pn.set("float16",Uint16Array)}}}),Qu,Xu,Kb=Ue(()=>{hd(),Qu=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Br(e.type,e.data,r);case"cpu-pinned":return new Br({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Br({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Br({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Br({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Br,hd=Ue(()=>{Vb(),Wb(),Gb(),Kb(),Br=class{constructor(e,r,t){qu();let s,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=pn.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{let l=pn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(r,BigInt):o=l.from(r)}else if(r instanceof l)o=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=$i.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e}if(a===void 0)a=[o.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");i=a,this.cpuData=o,this.dataLocation="cpu"}let n=Qu(i);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=i,this.size=n}static async fromImage(e,r){return Vu(e,r)}static fromTexture(e,r){return Wu(e,r)}static fromGpuBuffer(e,r){return Gu(e,r)}static fromMLTensor(e,r){return Ku(e,r)}static fromPinnedBuffer(e,r,t){return Hu(e,r,t)}toDataURL(e){return ju(this,e)}toImageData(e){return Uu(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xu(this,e)}}}),ts,Ju=Ue(()=>{hd(),ts=Br}),ki,md,rs,Hr,Yu=Ue(()=>{Nu(),ki=(e,r)=>{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||console.timeStamp(`${e}::ORT::${r}`)},md=(e,r)=>{var i;let t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||md("BEGIN",e)},Hr=e=>{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||md("END",e)}}),Zu,Hb=Ue(()=>{Bu(),Ju(),Yu(),Zu=class wb{constructor(r){this.handler=r}async run(r,t,s){rs();let i={},n={};if(typeof r!="object"||r===null||r instanceof ts||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ts)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let d of t){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,p=Object.getOwnPropertyNames(t);for(let u of this.outputNames)if(p.indexOf(u)!==-1){let h=t[u];(h===null||h instanceof ts)&&(d=!0,o=!1,i[u]=h)}if(d){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of this.inputNames)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(o)for(let d of this.outputNames)i[d]=null;let a=await this.handler.run(r,i,n),l={};for(let d in a)if(Object.hasOwnProperty.call(a,d)){let p=a[d];p instanceof ts?l[d]=p:l[d]=new ts(p.type,p.data,p.dims)}return Hr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){rs();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,u=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-u,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await zu(o),d=await a.createInferenceSessionHandler(n,l);return Hr(),new wb(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),_d,qb=Ue(()=>{Hb(),_d=Zu}),Qb=Ue(()=>{}),Xb=Ue(()=>{}),Jb=Ue(()=>{}),Yb=Ue(()=>{}),ep={};Ci(ep,{InferenceSession:()=>_d,TRACE:()=>ki,TRACE_FUNC_BEGIN:()=>rs,TRACE_FUNC_END:()=>Hr,Tensor:()=>ts,env:()=>Vt,registerBackend:()=>un});var ss=Ue(()=>{Nb(),Ub(),qb(),Ju(),Qb(),Xb(),Yu(),Jb(),Yb()}),fd=Ue(()=>{}),tp={};Ci(tp,{default:()=>rp});var gd,wd,rp,Zb=Ue(()=>{var e;Fw(),hn(),Pd(),gd="ort-wasm-proxy-worker",wd=((e=globalThis.self)==null?void 0:e.name)===gd,wd&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":$d(s.wasm).then(()=>{Bc(s).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:n}=s;Rc(n,i).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:i}=s,n=Fa(i);postMessage({type:t,out:n});break}case"create":{let{model:i,options:n}=s;Nc(i,n).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":jc(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:n,inputs:o,outputIndices:a,options:l}=s;Vc(i,n,o,a,new Array(a.length).fill(null),l).then(d=>{d.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},Gc([...o,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":Wc(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),rp=wd?null:r=>new Worker(r??Rr,{type:"module",name:gd})}),sp={};Ci(sp,{default:()=>np});var yd,Md,np,ip,ev=Ue(()=>{var e,r;Md=(yd=self.location.href,async function(t={}){var ca;var s,i,n=t,o=new Promise((c,m)=>{s=c,i=m}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",d=l&&((ca=self.name)==null?void 0:ca.startsWith("em-pthread"));n.mountExternalData=(c,m)=>{c.startsWith("./")&&(c=c.substring(2)),(n.Bd||(n.Bd=new Map)).set(c,m)},n.unmountExternalData=()=>{delete n.Bd};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let u=()=>{let c=(v,C,I)=>(...W)=>{let se=Rt,ge=C==null?void 0:C();W=v(...W);let Ee=C==null?void 0:C();return ge!==Ee&&(v=Ee,I(ge),C=I=null),Rt!=se?new Promise((ze,Ye)=>{rn={resolve:ze,reject:Ye}}):W},m=v=>async(...C)=>{var I;try{if(n.Cd)throw Error("Session already started");let W=n.Cd={be:C[0],errors:[]},se=await v(...C);if(n.Cd!==W)throw Error("Session mismatch");(I=n.Dd)==null||I.flush();let ge=W.errors;if(0ze),0n._OrtCreateSession,v=>n._OrtCreateSession=v),n._OrtRun=m(c(n._OrtRun,()=>n._OrtRun,v=>n._OrtRun=v)),n._OrtRunWithBinding=m(c(n._OrtRunWithBinding,()=>n._OrtRunWithBinding,v=>n._OrtRunWithBinding=v)),n._OrtBindInput=c(n._OrtBindInput,()=>n._OrtBindInput,v=>n._OrtBindInput=v),u=void 0};n.jsepInit=(c,m)=>{if(u==null||u(),c==="webgpu"){[n.Dd,n.Rd,n.Vd,n.Hd,n.Ud,n.hc,n.Wd,n.Zd,n.Sd,n.Td,n.Xd]=m;let v=n.Dd;n.jsepRegisterBuffer=(C,I,W,se)=>v.registerBuffer(C,I,W,se),n.jsepGetBuffer=C=>v.getBuffer(C),n.jsepCreateDownloader=(C,I,W)=>v.createDownloader(C,I,W),n.jsepOnCreateSession=C=>{v.onCreateSession(C)},n.jsepOnReleaseSession=C=>{v.onReleaseSession(C)},n.jsepOnRunStart=C=>v.onRunStart(C),n.$d=(C,I)=>{v.upload(C,I)}}else if(c==="webnn"){[n.Dd,n.Yd,n.Id,n.jsepEnsureTensor,n.Jd,n.jsepDownloadTensor]=m,n.jsepReleaseTensorId=n.Id,n.jsepUploadTensor=n.Jd;let v=n.Dd;n.jsepOnRunStart=C=>v.onRunStart(C),n.jsepOnRunEnd=v.onRunEnd.bind(v),n.jsepRegisterMLContext=(C,I)=>{v.registerMLContext(C,I)},n.jsepOnReleaseSession=C=>{v.onReleaseSession(C)},n.jsepCreateMLTensorDownloader=(C,I)=>v.createMLTensorDownloader(C,I),n.jsepRegisterMLTensor=(C,I,W,se)=>v.registerMLTensor(C,I,W,se),n.jsepCreateMLContext=C=>v.createMLContext(C),n.jsepRegisterMLConstant=(C,I,W,se,ge)=>v.registerMLConstant(C,I,W,se,ge,n.Bd),n.jsepRegisterGraphInput=v.registerGraphInput.bind(v),n.jsepIsGraphInput=v.isGraphInput.bind(v),n.jsepCreateTemporaryTensor=v.createTemporaryTensor.bind(v)}};var h,w,f=Object.assign({},n),P=(c,m)=>{throw m},A="";(a||l)&&(l?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),yd&&(A=yd),A=A.startsWith("blob:")?"":A.slice(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(w=c=>{var m=new XMLHttpRequest;return m.open("GET",c,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),h=async c=>{if(we(c))return new Promise((v,C)=>{var I=new XMLHttpRequest;I.open("GET",c,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?v(I.response):C(I.status)},I.onerror=C,I.send(null)});var m=await fetch(c,{credentials:"same-origin"});if(m.ok)return m.arrayBuffer();throw Error(m.status+" : "+m.url)});var b=console.log.bind(console),y=console.error.bind(console),$=b,T=y;Object.assign(n,f),f=null;var g,M,E,k,B,N,J,q,V,Y,H,Q,ie,le=n.wasmBinary,ae=!1,we=c=>c.startsWith("file://");function R(){return g.buffer!=k.buffer&&K(),k}function O(){return g.buffer!=k.buffer&&K(),B}function G(){return g.buffer!=k.buffer&&K(),N}function ne(){return g.buffer!=k.buffer&&K(),J}function X(){return g.buffer!=k.buffer&&K(),q}function ye(){return g.buffer!=k.buffer&&K(),V}function _e(){return g.buffer!=k.buffer&&K(),Y}function ke(){return g.buffer!=k.buffer&&K(),ie}if(d){let c=function(m){try{var v=m.data,C=v.yd;if(C==="load"){let I=[];self.onmessage=W=>I.push(W),self.startWorker=()=>{postMessage({yd:"loaded"});for(let W of I)c(W);self.onmessage=c};for(let W of v.Od)n[W]&&!n[W].proxy||(n[W]=(...se)=>{postMessage({yd:"callHandler",Nd:W,args:se})},W=="print"&&($=n[W]),W=="printErr"&&(T=n[W]));g=v.he,K(),He(v.ie)}else if(C==="run"){Fs(v.xd),ri(v.xd,0,0,1,0,0),jt(),Ot(v.xd),Me||(ti(),Me=!0);try{Dr(v.de,v.Fd)}catch(I){if(I!="unwind")throw I}}else v.target!=="setimmediate"&&(C==="checkMailbox"?Me&&Ut():C&&(T(`worker: received unknown command ${C}`),T(v)))}catch(I){throw uo(),I}};var He,Me=!1;T=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({yd:"alert",text:m.join(" "),fe:In()})},self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=c}function K(){var c=g.buffer;n.HEAP8=k=new Int8Array(c),n.HEAP16=N=new Int16Array(c),n.HEAPU8=B=new Uint8Array(c),n.HEAPU16=J=new Uint16Array(c),n.HEAP32=q=new Int32Array(c),n.HEAPU32=V=new Uint32Array(c),n.HEAPF32=Y=new Float32Array(c),n.HEAPF64=ie=new Float64Array(c),n.HEAP64=H=new BigInt64Array(c),n.HEAPU64=Q=new BigUint64Array(c)}function U(){d?startWorker(n):Oe.Bb()}d||(g=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),K());var pe,Pe=0,Te=null;function Ae(){if(--Pe==0&&Te){var c=Te;Te=null,c()}}function Ie(c){throw T(c="Aborted("+c+")"),ae=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),i(c),c}function Le(){return{a:{Ta:D,Va:Ve,W:Os,la:dt,b:xs,u:Ts,R:Es,Za:Ds,d:mr,pb:et,g:Ur,T:Ir,Ga:ps,lb:ms,nb:_s,Ha:Qr,Ea:Ps,wb:qs,Da:Qs,pa:Xs,mb:Js,jb:fs,Fa:Ys,kb:Zs,Ma:Cs,za:Tn,eb:En,cb:Ss,ya:ue,V:F,N:j,db:te,ma:ht,fb:Ct,zb:kt,hb:vr,qb:Yr,ab:xr,Aa:gs,yb:Ot,Ja:Gt,S:Zr,Wa:ws,$:za,H:Ba,E:Na,l:Jr,F:Gi,B:Va,X:Ki,J:Wa,v:Hi,O:Jc,D:Ga,t:qi,A:Ka,z:Kn,w:Ha,r:qa,tb:Qa,ub:Xa,vb:Hn,rb:qn,sb:Yi,bb:Zi,Oa:Yc,La:Zc,y:Ya,ja:Za,Ba:el,Ka:Ja,qa:tl,Ia:rl,ib:Jn,U:js,fa:sl,Sa:nl,gb:il,Qa:to,Pa:ol,Ab:so,Ca:Zn,ob:je,aa:no,oa:io,xb:ei,na:oo,$a:Pl,ia:aa,sa:zl,ga:ra,da:kl,ua:Ll,p:xl,e:ul,c:dl,ea:na,f:pl,n:hl,k:ea,Y:_l,ka:bl,j:Tl,wa:Sl,Ra:da,ca:oa,Ua:Rl,P:$l,K:Zo,_:ia,Q:El,Z:Ol,x:fl,m:cl,va:Al,i:Jo,h:ml,ra:Bl,ta:la,o:Yo,q:gl,s:yl,I:Ml,C:ta,L:vl,xa:Cl,_a:sa,G:Fl,Ya:xi,ba:Dl,M:wl,Xa:Il,ha:ao,a:g,Na:Re}}}var Ne={1320978:()=>typeof wasmOffsetConverter<"u",1321035:(c,m,v,C,I)=>{if(n===void 0||!n.Bd)return 1;if((c=zt(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=n.Bd.get(c)))return 2;if(m=Number(m>>>0),v=Number(v>>>0),C=Number(C>>>0),m+v>c.byteLength)return 3;try{let W=c.subarray(m,m+v);switch(I){case 0:O().set(W,C>>>0);break;case 1:n.$d(C,W);break;default:return 4}return 0}catch{return 4}},1321750:(c,m,v)=>{n.Jd(c,O().subarray(m>>>0,m+v>>>0))},1321813:()=>n.Yd(),1321854:c=>{n.Id(c)},1321890:()=>{n.Sd()},1321921:()=>{n.Td()},1321950:()=>{n.Xd()},1321975:c=>n.Rd(c),1322008:c=>n.Vd(c),1322040:(c,m,v)=>{n.Hd(Number(c),Number(m),Number(v),!0)},1322103:(c,m,v)=>{n.Hd(Number(c),Number(m),Number(v))},1322160:c=>{n.hc("Abs",c,void 0)},1322211:c=>{n.hc("Neg",c,void 0)},1322262:c=>{n.hc("Floor",c,void 0)},1322315:c=>{n.hc("Ceil",c,void 0)},1322367:c=>{n.hc("Reciprocal",c,void 0)},1322425:c=>{n.hc("Sqrt",c,void 0)},1322477:c=>{n.hc("Exp",c,void 0)},1322528:c=>{n.hc("Erf",c,void 0)},1322579:c=>{n.hc("Sigmoid",c,void 0)},1322634:(c,m,v)=>{n.hc("HardSigmoid",c,{alpha:m,beta:v})},1322713:c=>{n.hc("Log",c,void 0)},1322764:c=>{n.hc("Sin",c,void 0)},1322815:c=>{n.hc("Cos",c,void 0)},1322866:c=>{n.hc("Tan",c,void 0)},1322917:c=>{n.hc("Asin",c,void 0)},1322969:c=>{n.hc("Acos",c,void 0)},1323021:c=>{n.hc("Atan",c,void 0)},1323073:c=>{n.hc("Sinh",c,void 0)},1323125:c=>{n.hc("Cosh",c,void 0)},1323177:c=>{n.hc("Asinh",c,void 0)},1323230:c=>{n.hc("Acosh",c,void 0)},1323283:c=>{n.hc("Atanh",c,void 0)},1323336:c=>{n.hc("Tanh",c,void 0)},1323388:c=>{n.hc("Not",c,void 0)},1323439:(c,m,v)=>{n.hc("Clip",c,{min:m,max:v})},1323508:c=>{n.hc("Clip",c,void 0)},1323560:(c,m)=>{n.hc("Elu",c,{alpha:m})},1323618:c=>{n.hc("Gelu",c,void 0)},1323670:c=>{n.hc("Relu",c,void 0)},1323722:(c,m)=>{n.hc("LeakyRelu",c,{alpha:m})},1323786:(c,m)=>{n.hc("ThresholdedRelu",c,{alpha:m})},1323856:(c,m)=>{n.hc("Cast",c,{to:m})},1323914:c=>{n.hc("Add",c,void 0)},1323965:c=>{n.hc("Sub",c,void 0)},1324016:c=>{n.hc("Mul",c,void 0)},1324067:c=>{n.hc("Div",c,void 0)},1324118:c=>{n.hc("Pow",c,void 0)},1324169:c=>{n.hc("Equal",c,void 0)},1324222:c=>{n.hc("Greater",c,void 0)},1324277:c=>{n.hc("GreaterOrEqual",c,void 0)},1324339:c=>{n.hc("Less",c,void 0)},1324391:c=>{n.hc("LessOrEqual",c,void 0)},1324450:(c,m,v,C,I)=>{n.hc("ReduceMean",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324625:(c,m,v,C,I)=>{n.hc("ReduceMax",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324799:(c,m,v,C,I)=>{n.hc("ReduceMin",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324973:(c,m,v,C,I)=>{n.hc("ReduceProd",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325148:(c,m,v,C,I)=>{n.hc("ReduceSum",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325322:(c,m,v,C,I)=>{n.hc("ReduceL1",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325495:(c,m,v,C,I)=>{n.hc("ReduceL2",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325668:(c,m,v,C,I)=>{n.hc("ReduceLogSum",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325845:(c,m,v,C,I)=>{n.hc("ReduceSumSquare",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326025:(c,m,v,C,I)=>{n.hc("ReduceLogSumExp",c,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326205:c=>{n.hc("Where",c,void 0)},1326258:(c,m,v)=>{n.hc("Transpose",c,{perm:m?Array.from(X().subarray(Number(m)>>>0,Number(v)>>>0)):[]})},1326382:(c,m,v,C)=>{n.hc("DepthToSpace",c,{blocksize:m,mode:zt(v),format:C?"NHWC":"NCHW"})},1326515:(c,m,v,C)=>{n.hc("DepthToSpace",c,{blocksize:m,mode:zt(v),format:C?"NHWC":"NCHW"})},1326648:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt,Pr)=>{n.hc("ConvTranspose",c,{format:Ee?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernelShape:[I],pads:[W,se],strides:[ge],wIsConst:()=>!!R()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:gt?Array.from(X().subarray(Number(gt)>>>0,Number(Bt)>>>0)):[],activation:zt(Pr)})},1327081:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>{n.hc("ConvTranspose",c,{format:ge?"NHWC":"NCHW",autoPad:m,dilations:Array.from(X().subarray(Number(v)>>>0,2+(Number(v)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(se)>>>0,2+(Number(se)>>>0)>>>0)),wIsConst:()=>!!R()[Ee>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[],activation:zt(Bt)})},1327742:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt,Pr)=>{n.hc("ConvTranspose",c,{format:Ee?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernelShape:[I],pads:[W,se],strides:[ge],wIsConst:()=>!!R()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:gt?Array.from(X().subarray(Number(gt)>>>0,Number(Bt)>>>0)):[],activation:zt(Pr)})},1328175:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>{n.hc("ConvTranspose",c,{format:ge?"NHWC":"NCHW",autoPad:m,dilations:Array.from(X().subarray(Number(v)>>>0,2+(Number(v)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(se)>>>0,2+(Number(se)>>>0)>>>0)),wIsConst:()=>!!R()[Ee>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[],activation:zt(Bt)})},1328836:(c,m)=>{n.hc("GlobalAveragePool",c,{format:m?"NHWC":"NCHW"})},1328927:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>{n.hc("AveragePool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ge?Array.from(X().subarray(Number(ge)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1329406:(c,m)=>{n.hc("GlobalAveragePool",c,{format:m?"NHWC":"NCHW"})},1329497:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>{n.hc("AveragePool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ge?Array.from(X().subarray(Number(ge)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1329976:(c,m)=>{n.hc("GlobalMaxPool",c,{format:m?"NHWC":"NCHW"})},1330063:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>{n.hc("MaxPool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ge?Array.from(X().subarray(Number(ge)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1330538:(c,m)=>{n.hc("GlobalMaxPool",c,{format:m?"NHWC":"NCHW"})},1330625:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>{n.hc("MaxPool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ge?Array.from(X().subarray(Number(ge)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1331100:(c,m,v,C,I)=>{n.hc("Gemm",c,{alpha:m,beta:v,transA:C,transB:I})},1331204:c=>{n.hc("MatMul",c,void 0)},1331258:(c,m,v,C)=>{n.hc("ArgMax",c,{keepDims:!!m,selectLastIndex:!!v,axis:C})},1331366:(c,m,v,C)=>{n.hc("ArgMin",c,{keepDims:!!m,selectLastIndex:!!v,axis:C})},1331474:(c,m)=>{n.hc("Softmax",c,{axis:m})},1331537:(c,m)=>{n.hc("Concat",c,{axis:m})},1331597:(c,m,v,C,I)=>{n.hc("Split",c,{axis:m,numOutputs:v,splitSizes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1331753:c=>{n.hc("Expand",c,void 0)},1331807:(c,m)=>{n.hc("Gather",c,{axis:Number(m)})},1331878:(c,m)=>{n.hc("GatherElements",c,{axis:Number(m)})},1331957:(c,m)=>{n.hc("GatherND",c,{batch_dims:Number(m)})},1332036:(c,m,v,C,I,W,se,ge,Ee,ze,Ye)=>{n.hc("Resize",c,{antialias:m,axes:v?Array.from(X().subarray(Number(v)>>>0,Number(C)>>>0)):[],coordinateTransformMode:zt(I),cubicCoeffA:W,excludeOutside:se,extrapolationValue:ge,keepAspectRatioPolicy:zt(Ee),mode:zt(ze),nearestMode:zt(Ye)})},1332398:(c,m,v,C,I,W,se)=>{n.hc("Slice",c,{starts:m?Array.from(X().subarray(Number(m)>>>0,Number(v)>>>0)):[],ends:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[],axes:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[]})},1332662:c=>{n.hc("Tile",c,void 0)},1332714:(c,m,v)=>{n.hc("InstanceNormalization",c,{epsilon:m,format:v?"NHWC":"NCHW"})},1332828:(c,m,v)=>{n.hc("InstanceNormalization",c,{epsilon:m,format:v?"NHWC":"NCHW"})},1332942:c=>{n.hc("Range",c,void 0)},1332995:(c,m)=>{n.hc("Einsum",c,{equation:zt(m)})},1333076:(c,m,v,C,I)=>{n.hc("Pad",c,{mode:m,value:v,pads:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1333219:(c,m,v,C,I,W)=>{n.hc("BatchNormalization",c,{epsilon:m,momentum:v,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333388:(c,m,v,C,I,W)=>{n.hc("BatchNormalization",c,{epsilon:m,momentum:v,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333557:(c,m,v)=>{n.hc("CumSum",c,{exclusive:Number(m),reverse:Number(v)})},1333654:(c,m,v)=>{n.hc("DequantizeLinear",c,{axis:m,blockSize:v})},1333744:(c,m,v,C,I)=>{n.hc("GridSample",c,{align_corners:m,mode:zt(v),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1333914:(c,m,v,C,I)=>{n.hc("GridSample",c,{align_corners:m,mode:zt(v),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1334084:(c,m)=>{n.hc("ScatterND",c,{reduction:zt(m)})},1334169:(c,m,v,C,I,W,se,ge,Ee)=>{n.hc("Attention",c,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:I,doRotary:W,qkvHiddenSizes:se?Array.from(X().subarray(Number(ge)>>>0,Number(ge)+se>>>0)):[],pastPresentShareBuffer:!!Ee})},1334441:c=>{n.hc("BiasAdd",c,void 0)},1334496:c=>{n.hc("BiasSplitGelu",c,void 0)},1334557:c=>{n.hc("FastGelu",c,void 0)},1334613:(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt,Pr,an)=>{n.hc("Conv",c,{format:ot?"NHWC":"NCHW",auto_pad:m,dilations:v?Array.from(X().subarray(Number(v)>>>0,Number(C)>>>0)):[],group:I,kernel_shape:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],pads:ge?Array.from(X().subarray(Number(ge)>>>0,Number(Ee)>>>0)):[],strides:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],w_is_const:()=>!!R()[Number(gt)>>>0],activation:zt(Bt),activation_params:Pr?Array.from(_e().subarray(Number(Pr)>>>0,Number(an)>>>0)):[]})},1335197:c=>{n.hc("Gelu",c,void 0)},1335249:(c,m,v,C,I,W,se,ge,Ee)=>{n.hc("GroupQueryAttention",c,{numHeads:m,kvNumHeads:v,scale:C,softcap:I,doRotary:W,rotaryInterleaved:se,smoothSoftmax:ge,localWindowSize:Ee})},1335466:(c,m,v,C)=>{n.hc("LayerNormalization",c,{axis:m,epsilon:v,simplified:!!C})},1335577:(c,m,v,C)=>{n.hc("LayerNormalization",c,{axis:m,epsilon:v,simplified:!!C})},1335688:(c,m,v,C,I,W)=>{n.hc("MatMulNBits",c,{k:m,n:v,accuracyLevel:C,bits:I,blockSize:W})},1335815:(c,m,v,C,I,W)=>{n.hc("MultiHeadAttention",c,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:I,doRotary:W})},1335974:(c,m)=>{n.hc("QuickGelu",c,{alpha:m})},1336038:(c,m,v,C,I)=>{n.hc("RotaryEmbedding",c,{interleaved:!!m,numHeads:v,rotaryEmbeddingDim:C,scale:I})},1336177:(c,m,v)=>{n.hc("SkipLayerNormalization",c,{epsilon:m,simplified:!!v})},1336279:(c,m,v)=>{n.hc("SkipLayerNormalization",c,{epsilon:m,simplified:!!v})},1336381:(c,m,v,C)=>{n.hc("GatherBlockQuantized",c,{gatherAxis:m,quantizeAxis:v,blockSize:C})},1336502:c=>{n.Wd(c)},1336536:(c,m)=>n.Zd(Number(c),Number(m),n.Cd.be,n.Cd.errors)};function Ve(c,m,v){return Vi(async()=>{await n.Ud(Number(c),Number(m),Number(v))})}function D(){return typeof wasmOffsetConverter<"u"}class Z{constructor(m){re(this,"name","ExitStatus");this.message=`Program terminated with exit(${m})`,this.status=m}}var z=c=>{c.terminate(),c.onmessage=()=>{}},ee=[],ce=c=>{Qe.length==0&&(ds(),dr(Qe[0]));var m=Qe.pop();if(!m)return 6;Xe.push(m),wt[c.xd]=m,m.xd=c.xd;var v={yd:"run",de:c.ce,Fd:c.Fd,xd:c.xd};return m.postMessage(v,c.Ld),0},be=0,ve=(c,m,...v)=>{for(var C=2*v.length,I=_t(),W=An(8*C),se=W>>>3,ge=0;ge>>0]=Ee)}return c=si(c,0,C,W,m),mt(I),c};function Re(c){if(d)return ve(0,1,c);if(E=c,!(0{if(E=c,d)throw Fe(c),"unwind";Re(c)},Qe=[],Xe=[],ut=[],wt={},nr=c=>{var m=c.xd;delete wt[m],Qe.push(c),Xe.splice(Xe.indexOf(c),1),c.xd=0,po(m)};function jt(){ut.forEach(c=>c())}var dr=c=>new Promise(m=>{c.onmessage=I=>{var W=(I=I.data).yd;if(I.Ed&&I.Ed!=In()){var se=wt[I.Ed];se?se.postMessage(I,I.Ld):T(`Internal error! Worker sent a message "${W}" to target pthread ${I.Ed}, but that thread no longer exists!`)}else W==="checkMailbox"?Ut():W==="spawnThread"?ce(I):W==="cleanupThread"?nr(wt[I.ee]):W==="loaded"?(c.loaded=!0,m(c)):W==="alert"?alert(`Thread ${I.fe}: ${I.text}`):I.target==="setimmediate"?c.postMessage(I):W==="callHandler"?n[I.Nd](...I.args):W&&T(`worker sent an unknown command ${W}`)},c.onerror=I=>{throw T(`worker sent an error! ${I.filename}:${I.lineno}: ${I.message}`),I};var v,C=[];for(v of[])n.propertyIsEnumerable(v)&&C.push(v);c.postMessage({yd:"load",Od:C,he:g,ie:M})});function ds(){var c=new Worker((()=>{let m=URL;return self.location.href>"file:"&&self.location.href<"file;"?new m("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Qe.push(c)}var Fs=c=>{K();var m=ye()[c+52>>>2>>>0];c=ye()[c+56>>>2>>>0],mo(m,m-c),mt(m)},Dr=(c,m)=>{be=0,c=li(c,m),0>>=0);if(R()[m.wd+12>>>0]==0){var v=1;R()[m.wd+12>>>0]=v}return v=0,R()[m.wd+13>>>0]=v,cs.push(m),oi(c),go(c)}var jr=0,dt=()=>{ft(0,0);var c=cs.pop();_o(c.Gd),jr=0};class qr{constructor(m){this.Gd=m,this.wd=m-24}}function Ur(c){throw jr||(jr=c>>>0),jr}var us=c=>{var m=jr;if(!m)return Us(0),0;var v=new qr(m);ye()[v.wd+16>>>2>>>0]=m;var C=ye()[v.wd+4>>>2>>>0];if(!C)return Us(0),m;for(var I of c){if(I===0||I===C)break;if(fo(I,C,v.wd+16))return Us(I),m}return Us(C),m};function xs(){return us([])}function Ts(c){return us([c>>>0])}function Es(c,m){return us([c>>>0,m>>>0])}var Ds=()=>{var c=cs.pop();c||Ie("no exception to throw");var m=c.Gd;if(R()[c.wd+13>>>0]==0){cs.push(c);var v=1;R()[c.wd+13>>>0]=v,v=0,R()[c.wd+12>>>0]=v}throw jr=m};function mr(c,m,v){var C=new qr(c>>>=0);throw m>>>=0,v>>>=0,ye()[C.wd+16>>>2>>>0]=0,ye()[C.wd+4>>>2>>>0]=m,ye()[C.wd+8>>>2>>>0]=v,jr=c}function Be(c,m,v,C){return d?ve(2,1,c,m,v,C):et(c,m,v,C)}function et(c,m,v,C){if(c>>>=0,v>>>=0,C>>>=0,p===void 0)return 6;var I=[];return d&&I.length===0?Be(c,m>>>=0,v,C):(c={ce:v,xd:c,Fd:C,Ld:I},d?(c.yd="spawnThread",postMessage(c,I),0):ce(c))}var it=typeof TextDecoder<"u"?new TextDecoder:void 0,rr=(c,m=0,v=NaN)=>{var C=(m>>>=0)+v;for(v=m;c[v]&&!(v>=C);)++v;if(16(I=(240&I)==224?(15&I)<<12|W<<6|se:(7&I)<<18|W<<12|se<<6|63&c[m++])?C+=String.fromCharCode(I):(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I))}}else C+=String.fromCharCode(I)}return C},zt=(c,m)=>(c>>>=0)?rr(O(),c,m):"";function Ir(c,m,v){return d?ve(3,1,c,m,v):0}function ps(c,m){if(d)return ve(4,1,c,m)}var hs=c=>{for(var m=0,v=0;v=C?m++:2047>=C?m+=2:55296<=C&&57343>=C?(m+=4,++v):m+=3}return m},Er=(c,m,v)=>{var C=O();if(m>>>=0,0=se&&(se=65536+((1023&se)<<10)|1023&c.charCodeAt(++W)),127>=se){if(m>=v)break;C[m++>>>0]=se}else{if(2047>=se){if(m+1>=v)break;C[m++>>>0]=192|se>>6}else{if(65535>=se){if(m+2>=v)break;C[m++>>>0]=224|se>>12}else{if(m+3>=v)break;C[m++>>>0]=240|se>>18,C[m++>>>0]=128|se>>12&63}C[m++>>>0]=128|se>>6&63}C[m++>>>0]=128|63&se}}C[m>>>0]=0,c=m-I}else c=0;return c};function ms(c,m){if(d)return ve(5,1,c,m)}function _s(c,m,v){if(d)return ve(6,1,c,m,v)}function Qr(c,m,v){return d?ve(7,1,c,m,v):0}function Ps(c,m){if(d)return ve(8,1,c,m)}function qs(c,m,v){if(d)return ve(9,1,c,m,v)}function Qs(c,m,v,C){if(d)return ve(10,1,c,m,v,C)}function Xs(c,m,v,C){if(d)return ve(11,1,c,m,v,C)}function Js(c,m,v,C){if(d)return ve(12,1,c,m,v,C)}function fs(c){if(d)return ve(13,1,c)}function Ys(c,m){if(d)return ve(14,1,c,m)}function Zs(c,m,v){if(d)return ve(15,1,c,m,v)}var en,Lr,Cs=()=>Ie(""),br=c=>{for(var m="";O()[c>>>0];)m+=en[O()[c++>>>0]];return m},Ls={},zs={};function Ar(c,m,v={}){return function(C,I,W={}){var se=I.name;if(!C)throw new Lr(`type "${se}" must have a positive integer typeid pointer`);if(zs.hasOwnProperty(C)){if(W.Pd)return;throw new Lr(`Cannot register type '${se}' twice`)}zs[C]=I,Ls.hasOwnProperty(C)&&(I=Ls[C],delete Ls[C],I.forEach(ge=>ge()))}(c,m,v)}var Xr=(c,m,v)=>{switch(m){case 1:return v?C=>R()[C>>>0]:C=>O()[C>>>0];case 2:return v?C=>G()[C>>>1>>>0]:C=>ne()[C>>>1>>>0];case 4:return v?C=>X()[C>>>2>>>0]:C=>ye()[C>>>2>>>0];case 8:return v?C=>H[C>>>3]:C=>Q[C>>>3];default:throw new TypeError(`invalid integer width (${m}): ${c}`)}};function Tn(c,m,v){v>>>=0,Ar(c>>>=0,{name:m=br(m>>>0),fromWireType:C=>C,toWireType:function(C,I){if(typeof I!="bigint"&&typeof I!="number")throw I=I===null?"null":(C=typeof I)=="object"||C==="array"||C==="function"?I.toString():""+I,new TypeError(`Cannot convert "${I}" to ${this.name}`);return typeof I=="number"&&(I=BigInt(I)),I},zd:zr,readValueFromPointer:Xr(m,v,m.indexOf("u")==-1),Ad:null})}var zr=8;function En(c,m,v,C){Ar(c>>>=0,{name:m=br(m>>>0),fromWireType:function(I){return!!I},toWireType:function(I,W){return W?v:C},zd:zr,readValueFromPointer:function(I){return this.fromWireType(O()[I>>>0])},Ad:null})}var Bs=[],Fr=[];function Jr(c){9<(c>>>=0)&&--Fr[c+1]==0&&(Fr[c]=void 0,Bs.push(c))}var cr=c=>{if(!c)throw new Lr("Cannot use deleted val. handle = "+c);return Fr[c]},_r=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Bs.pop()||Fr.length;return Fr[m]=c,Fr[m+1]=1,m}};function Rs(c){return this.fromWireType(ye()[c>>>2>>>0])}var Pn={name:"emscripten::val",fromWireType:c=>{var m=cr(c);return Jr(c),m},toWireType:(c,m)=>_r(m),zd:zr,readValueFromPointer:Rs,Ad:null};function Ss(c){return Ar(c>>>0,Pn)}var Cn=(c,m)=>{switch(m){case 4:return function(v){return this.fromWireType(_e()[v>>>2>>>0])};case 8:return function(v){return this.fromWireType(ke()[v>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${c}`)}};function ue(c,m,v){v>>>=0,Ar(c>>>=0,{name:m=br(m>>>0),fromWireType:C=>C,toWireType:(C,I)=>I,zd:zr,readValueFromPointer:Cn(m,v),Ad:null})}function F(c,m,v,C,I){if(c>>>=0,v>>>=0,m=br(m>>>0),I===-1&&(I=4294967295),I=ge=>ge,C===0){var W=32-8*v;I=ge=>ge<>>W}var se=m.includes("unsigned")?function(ge,Ee){return Ee>>>0}:function(ge,Ee){return Ee};Ar(c,{name:m,fromWireType:I,toWireType:se,zd:zr,readValueFromPointer:Xr(m,v,C!==0),Ad:null})}function j(c,m,v){function C(W){var se=ye()[W>>>2>>>0];return W=ye()[W+4>>>2>>>0],new I(R().buffer,W,se)}var I=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Ar(c>>>=0,{name:v=br(v>>>0),fromWireType:C,zd:zr,readValueFromPointer:C},{Pd:!0})}function te(c,m){Ar(c>>>=0,{name:m=br(m>>>0),fromWireType:function(v){for(var C,I=ye()[v>>>2>>>0],W=v+4,se=W,ge=0;ge<=I;++ge){var Ee=W+ge;ge!=I&&O()[Ee>>>0]!=0||(se=zt(se,Ee-se),C===void 0?C=se:(C+="\0",C+=se),se=Ee+1)}return Vr(v),C},toWireType:function(v,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var I=typeof C=="string";if(!(I||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new Lr("Cannot pass non-string to std::string");var W=I?hs(C):C.length,se=on(4+W+1),ge=se+4;if(ye()[se>>>2>>>0]=W,I)Er(C,ge,W+1);else if(I)for(I=0;I>>0]=Ee}else for(I=0;I>>0]=C[I];return v!==null&&v.push(Vr,se),se},zd:zr,readValueFromPointer:Rs,Ad(v){Vr(v)}})}var de=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,he=(c,m)=>{for(var v=c>>1,C=v+m/2;!(v>=C)&&ne()[v>>>0];)++v;if(32<(v<<=1)-c&&de)return de.decode(O().slice(c,v));for(v="",C=0;!(C>=m/2);++C){var I=G()[c+2*C>>>1>>>0];if(I==0)break;v+=String.fromCharCode(I)}return v},Ce=(c,m,v)=>{if(v??(v=2147483647),2>v)return 0;var C=m;v=(v-=2)<2*c.length?v/2:c.length;for(var I=0;I>>1>>>0]=W,m+=2}return G()[m>>>1>>>0]=0,m-C},We=c=>2*c.length,qe=(c,m)=>{for(var v=0,C="";!(v>=m/4);){var I=X()[c+4*v>>>2>>>0];if(I==0)break;++v,65536<=I?(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I)):C+=String.fromCharCode(I)}return C},Ke=(c,m,v)=>{if(m>>>=0,v??(v=2147483647),4>v)return 0;var C=m;v=C+v-4;for(var I=0;I=W&&(W=65536+((1023&W)<<10)|1023&c.charCodeAt(++I)),X()[m>>>2>>>0]=W,(m+=4)+4>v)break}return X()[m>>>2>>>0]=0,m-C},Ze=c=>{for(var m=0,v=0;v=C&&++v,m+=4}return m};function ht(c,m,v){if(c>>>=0,m>>>=0,v=br(v>>>=0),m===2)var C=he,I=Ce,W=We,se=ge=>ne()[ge>>>1>>>0];else m===4&&(C=qe,I=Ke,W=Ze,se=ge=>ye()[ge>>>2>>>0]);Ar(c,{name:v,fromWireType:ge=>{for(var Ee,ze=ye()[ge>>>2>>>0],Ye=ge+4,ot=0;ot<=ze;++ot){var gt=ge+4+ot*m;ot!=ze&&se(gt)!=0||(Ye=C(Ye,gt-Ye),Ee===void 0?Ee=Ye:(Ee+="\0",Ee+=Ye),Ye=gt+m)}return Vr(ge),Ee},toWireType:(ge,Ee)=>{if(typeof Ee!="string")throw new Lr(`Cannot pass non-string to C++ string type ${v}`);var ze=W(Ee),Ye=on(4+ze+m);return ye()[Ye>>>2>>>0]=ze/m,I(Ee,Ye+4,ze+m),ge!==null&&ge.push(Vr,Ye),Ye},zd:zr,readValueFromPointer:Rs,Ad(ge){Vr(ge)}})}function Ct(c,m){Ar(c>>>=0,{Qd:!0,name:m=br(m>>>0),zd:0,fromWireType:()=>{},toWireType:()=>{}})}function kt(c){ri(c>>>0,!l,1,!a,131072,!1),jt()}var Wt=c=>{if(!ae)try{if(c(),!(0>>=0,typeof Atomics.ge=="function"&&(Atomics.ge(X(),c>>>2,c).value.then(Ut),c+=128,Atomics.store(X(),c>>>2,1))}var Ut=()=>{var c=In();c&&(Ot(c),Wt(ho))};function vr(c,m){(c>>>=0)==m>>>0?setTimeout(Ut):d?postMessage({Ed:c,yd:"checkMailbox"}):(c=wt[c])&&c.postMessage({yd:"checkMailbox"})}var fr=[];function Yr(c,m,v,C,I){for(m>>>=0,C/=2,fr.length=C,v=I>>>0>>>3,I=0;I>>0];return(m?Ne[m]:ll[c])(...fr)}var xr=()=>{be=0};function gs(c){c>>>=0,d?postMessage({yd:"cleanupThread",ee:c}):nr(wt[c])}function Gt(c){}var Zt=(c,m)=>{var v=zs[c];if(v===void 0)throw c=co(c),v=br(c),Vr(c),new Lr(`${m} has unknown type ${v}`);return v},gr=(c,m,v)=>{var C=[];return c=c.toWireType(C,v),C.length&&(ye()[m>>>2>>>0]=_r(C)),c};function Zr(c,m,v){return m>>>=0,v>>>=0,c=cr(c>>>0),m=Zt(m,"emval::as"),gr(m,v,c)}function ws(c,m){return m>>>=0,c=cr(c>>>0),(m=Zt(m,"emval::as")).toWireType(null,c)}var Ht=c=>{try{c()}catch(m){Ie(m)}},ur=0,Rt=null,Jt=0,qt=[],er={},ir={},tn=0,rn=null,La=[];function Vi(c){return function(m){if(!ae){if(ur===0){var v=!1,C=!1;m((I=0)=>{if(!ae&&(Jt=I,v=!0,C)){ur=2,Ht(()=>Qo(Rt)),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.resume(),I=!1;try{var W=function(){var Ee=X()[Rt+8>>>2>>>0];return Ee=Oe[ir[Ee]],--be,Ee()}()}catch(Ee){W=Ee,I=!0}var se=!1;if(!Rt){var ge=rn;ge&&(rn=null,(I?ge.reject:ge.resolve)(W),se=!0)}if(I&&!se)throw W}}),C=!0,v||(ur=1,Rt=function(){var I=on(65548),W=I+12;ye()[I>>>2>>>0]=W,ye()[I+4>>>2>>>0]=W+65536,W=qt[0];var se=er[W];return se===void 0&&(se=tn++,er[W]=se,ir[se]=W),W=se,X()[I+8>>>2>>>0]=W,I}(),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.pause(),Ht(()=>Ho(Rt)))}else ur===2?(ur=0,Ht(Xo),Vr(Rt),Rt=null,La.forEach(Wt)):Ie(`invalid state: ${ur}`);return Jt}}(m=>{c().then(m)})}function za(c){return c>>>=0,Vi(async()=>{var m=await cr(c);return _r(m)})}var ys=[];function Ba(c,m,v,C){return v>>>=0,C>>>=0,(c=ys[c>>>0])(null,m=cr(m>>>0),v,C)}var Ra={},Sn=c=>{var m=Ra[c];return m===void 0?br(c):m};function Na(c,m,v,C,I){return v>>>=0,C>>>=0,I>>>=0,(c=ys[c>>>0])(m=cr(m>>>0),m[v=Sn(v)],C,I)}var Wi=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Gi(c){return(c>>>=0)==0?_r(Wi()):(c=Sn(c),_r(Wi()[c]))}var ja=c=>{var m=ys.length;return ys.push(c),m},Ua=(c,m)=>{for(var v=Array(c),C=0;C>>2>>>0],"parameter "+C);return v},Gn=(c,m)=>Object.defineProperty(m,"name",{value:c});function Va(c,m,v){var C=(m=Ua(c,m>>>0)).shift();c--;var I=`return function (obj, func, destructorsRef, args) { +`,W=0,se=[];v===0&&se.push("obj");for(var ge=["retType"],Ee=[C],ze=0;zeYe.name).join(", ")}) => ${C.name}>`,ja(Gn(v,c))}function Ki(c){return c=Sn(c>>>0),_r(n[c])}function Wa(c,m){return m>>>=0,c=cr(c>>>0),m=cr(m),_r(c[m])}function Hi(c){9<(c>>>=0)&&(Fr[c+1]+=1)}function Jc(){return _r([])}function Ga(c){c=cr(c>>>0);for(var m=Array(c.length),v=0;v>>0))}function Ka(){return _r({})}function Kn(c){for(var m=cr(c>>>=0);m.length;){var v=m.pop();m.pop()(v)}Jr(c)}function Ha(c,m,v){m>>>=0,v>>>=0,c=cr(c>>>0),m=cr(m),v=cr(v),c[m]=v}function qa(c,m){return m>>>=0,c=(c=Zt(c>>>0,"_emval_take_value")).readValueFromPointer(m),_r(c)}function Qa(c,m){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),X()[m>>>2>>>0]=c.getUTCSeconds(),X()[m+4>>>2>>>0]=c.getUTCMinutes(),X()[m+8>>>2>>>0]=c.getUTCHours(),X()[m+12>>>2>>>0]=c.getUTCDate(),X()[m+16>>>2>>>0]=c.getUTCMonth(),X()[m+20>>>2>>>0]=c.getUTCFullYear()-1900,X()[m+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,X()[m+28>>>2>>>0]=c}var Qi=c=>c%4==0&&(c%100!=0||c%400==0),Xi=[0,31,60,91,121,152,182,213,244,274,305,335],Ji=[0,31,59,90,120,151,181,212,243,273,304,334];function Xa(c,m){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),X()[m>>>2>>>0]=c.getSeconds(),X()[m+4>>>2>>>0]=c.getMinutes(),X()[m+8>>>2>>>0]=c.getHours(),X()[m+12>>>2>>>0]=c.getDate(),X()[m+16>>>2>>>0]=c.getMonth(),X()[m+20>>>2>>>0]=c.getFullYear()-1900,X()[m+24>>>2>>>0]=c.getDay();var v=(Qi(c.getFullYear())?Xi:Ji)[c.getMonth()]+c.getDate()-1|0;X()[m+28>>>2>>>0]=v,X()[m+36>>>2>>>0]=-60*c.getTimezoneOffset(),v=new Date(c.getFullYear(),6,1).getTimezoneOffset();var C=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(v!=C&&c.getTimezoneOffset()==Math.min(C,v)),X()[m+32>>>2>>>0]=c}function Hn(c){c>>>=0;var m=new Date(X()[c+20>>>2>>>0]+1900,X()[c+16>>>2>>>0],X()[c+12>>>2>>>0],X()[c+8>>>2>>>0],X()[c+4>>>2>>>0],X()[c>>>2>>>0],0),v=X()[c+32>>>2>>>0],C=m.getTimezoneOffset(),I=new Date(m.getFullYear(),6,1).getTimezoneOffset(),W=new Date(m.getFullYear(),0,1).getTimezoneOffset(),se=Math.min(W,I);return 0>v?X()[c+32>>>2>>>0]=+(I!=W&&se==C):0>>2>>>0]=m.getDay(),v=(Qi(m.getFullYear())?Xi:Ji)[m.getMonth()]+m.getDate()-1|0,X()[c+28>>>2>>>0]=v,X()[c>>>2>>>0]=m.getSeconds(),X()[c+4>>>2>>>0]=m.getMinutes(),X()[c+8>>>2>>>0]=m.getHours(),X()[c+12>>>2>>>0]=m.getDate(),X()[c+16>>>2>>>0]=m.getMonth(),X()[c+20>>>2>>>0]=m.getYear(),c=m.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function qn(c,m,v,C,I,W,se){return d?ve(16,1,c,m,v,C,I,W,se):-52}function Yi(c,m,v,C,I,W){if(d)return ve(17,1,c,m,v,C,I,W)}var Ns={},js=()=>performance.timeOrigin+performance.now();function Zi(c,m){if(d)return ve(18,1,c,m);if(Ns[c]&&(clearTimeout(Ns[c].id),delete Ns[c]),!m)return 0;var v=setTimeout(()=>{delete Ns[c],Wt(()=>ii(c,performance.timeOrigin+performance.now()))},m);return Ns[c]={id:v,ke:m},0}function Yc(c,m,v,C){c>>>=0,m>>>=0,v>>>=0,C>>>=0;var I=new Date().getFullYear(),W=new Date(I,0,1).getTimezoneOffset();I=new Date(I,6,1).getTimezoneOffset();var se=Math.max(W,I);ye()[c>>>2>>>0]=60*se,X()[m>>>2>>>0]=+(W!=I),c=(m=ge=>{var Ee=Math.abs(ge);return`UTC${0<=ge?"-":"+"}${String(Math.floor(Ee/60)).padStart(2,"0")}${String(Ee%60).padStart(2,"0")}`})(W),m=m(I),IDate.now();function Zc(c,m,v){return 0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),H[v>>>0>>>3]=BigInt(Math.round(1e6*c)),0):28}var Qn=[],Xn=(c,m)=>{Qn.length=0;for(var v;v=O()[c++>>>0];){var C=v!=105;m+=(C&=v!=112)&&m%8?4:0,Qn.push(v==112?ye()[m>>>2>>>0]:v==106?H[m>>>3]:v==105?X()[m>>>2>>>0]:ke()[m>>>3>>>0]),m+=C?8:4}return Qn};function Ya(c,m,v){return c>>>=0,m=Xn(m>>>0,v>>>0),Ne[c](...m)}function Za(c,m,v){return c>>>=0,m=Xn(m>>>0,v>>>0),Ne[c](...m)}var el=()=>{};function tl(c,m){return T(zt(c>>>0,m>>>0))}var rl=()=>{throw be+=1,"unwind"};function Jn(){return 4294901760}var sl=()=>navigator.hardwareConcurrency;function nl(){return Ie("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function il(c){c>>>=0;var m=O().length;if(c<=m||4294901760=v;v*=2){var C=m*(1+.2/v);C=Math.min(C,c+100663296);e:{C=(Math.min(4294901760,65536*Math.ceil(Math.max(c,C)/65536))-g.buffer.byteLength+65535)/65536|0;try{g.grow(C),K();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var sn=()=>(Ie("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),nn={},eo=c=>{c.forEach(m=>{sn()})};function to(){var c=Error().stack.toString().split(` +`);return c[0]=="Error"&&c.shift(),eo(c),nn.Kd=sn(),nn.ae=c,nn.Kd}function ol(c,m,v){if(c>>>=0,m>>>=0,nn.Kd==c)var C=nn.ae;else(C=Error().stack.toString().split(` +`))[0]=="Error"&&C.shift(),eo(C);for(var I=3;C[I]&&sn()!=c;)++I;for(c=0;c>>2>>>0]=sn();return c}var Yn,$n={},ro=()=>{if(!Yn){var c,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in $n)$n[c]===void 0?delete m[c]:m[c]=$n[c];var v=[];for(c in m)v.push(`${c}=${m[c]}`);Yn=v}return Yn};function so(c,m){if(d)return ve(19,1,c,m);c>>>=0,m>>>=0;var v=0;return ro().forEach((C,I)=>{var W=m+v;for(I=ye()[c+4*I>>>2>>>0]=W,W=0;W>>0]=C.charCodeAt(W);R()[I>>>0]=0,v+=C.length+1}),0}function Zn(c,m){if(d)return ve(20,1,c,m);c>>>=0,m>>>=0;var v=ro();ye()[c>>>2>>>0]=v.length;var C=0;return v.forEach(I=>C+=I.length+1),ye()[m>>>2>>>0]=C,0}function no(c){return d?ve(21,1,c):52}function io(c,m,v,C){return d?ve(22,1,c,m,v,C):52}function ei(c,m,v,C){return d?ve(23,1,c,m,v,C):70}var al=[null,[],[]];function oo(c,m,v,C){if(d)return ve(24,1,c,m,v,C);m>>>=0,v>>>=0,C>>>=0;for(var I=0,W=0;W>>2>>>0],ge=ye()[m+4>>>2>>>0];m+=8;for(var Ee=0;Ee>>0],Ye=al[c];ze===0||ze===10?((c===1?$:T)(rr(Ye)),Ye.length=0):Ye.push(ze)}I+=ge}return ye()[C>>>2>>>0]=I,0}function ao(c){return c>>>0}d||function(){for(var c=n.numThreads-1;c--;)ds();ee.unshift(()=>{Pe++,function(m){d?m():Promise.all(Qe.map(dr)).then(m)}(()=>Ae())})}();for(var lo=Array(256),kn=0;256>kn;++kn)lo[kn]=String.fromCharCode(kn);en=lo,Lr=n.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},n.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},Fr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Fr.length/2-5-Bs.length;var Oe,ll=[Re,Fe,Be,Ir,ps,ms,_s,Qr,Ps,qs,Qs,Xs,Js,fs,Ys,Zs,qn,Yi,Zi,so,Zn,no,io,ei,oo];(async function(){function c(C,I){return Oe=C.exports,Oe=function(){var W=Oe,se={};for(let[ge,Ee]of Object.entries(W))se[ge]=typeof Ee=="function"?(...ze)=>{qt.push(ge);try{return Ee(...ze)}finally{ae||(qt.pop(),Rt&&ur===1&&qt.length===0&&(ur=0,be+=1,Ht(qo),typeof Fibers<"u"&&Fibers.le()))}}:Ee;return se}(),Oe=function(){var W=Oe,se=Ee=>ze=>Ee(ze)>>>0,ge=Ee=>()=>Ee()>>>0;return(W=Object.assign({},W)).Cb=se(W.Cb),W.fc=ge(W.fc),W.ic=se(W.ic),W.vc=se(W.vc),W.wc=ge(W.wc),W.Ac=se(W.Ac),W}(),ut.push(Oe.jc),M=I,Ae(),Oe}Pe++;var m=Le();if(n.instantiateWasm)return new Promise(C=>{n.instantiateWasm(m,(I,W)=>{c(I,W),C(I.exports)})});if(d)return new Promise(C=>{He=I=>{var W=new WebAssembly.Instance(I,Le());C(c(W,I))}});pe??(pe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",A):A+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",self.location.href).href);try{var v=await async function(C){var I=pe;if(!le&&typeof WebAssembly.instantiateStreaming=="function"&&!we(I))try{var W=fetch(I,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(W,C)}catch(se){T(`wasm streaming compile failed: ${se}`),T("falling back to ArrayBuffer instantiation")}return async function(se,ge){try{var Ee=await async function(ze){if(!le)try{var Ye=await h(ze);return new Uint8Array(Ye)}catch{}if(ze==pe&&le)ze=new Uint8Array(le);else{if(!w)throw"both async and sync fetching of the wasm failed";ze=w(ze)}return ze}(se);return await WebAssembly.instantiate(Ee,ge)}catch(ze){T(`failed to asynchronously prepare wasm: ${ze}`),Ie(ze)}}(I,C)}(m);return c(v.instance,v.module)}catch(C){return i(C),Promise.reject(C)}})();var co=c=>(co=Oe.Cb)(c),ti=()=>(ti=Oe.Db)();n._OrtInit=(c,m)=>(n._OrtInit=Oe.Eb)(c,m),n._OrtGetLastError=(c,m)=>(n._OrtGetLastError=Oe.Fb)(c,m),n._OrtCreateSessionOptions=(c,m,v,C,I,W,se,ge,Ee,ze)=>(n._OrtCreateSessionOptions=Oe.Gb)(c,m,v,C,I,W,se,ge,Ee,ze),n._OrtAppendExecutionProvider=(c,m)=>(n._OrtAppendExecutionProvider=Oe.Hb)(c,m),n._OrtAddFreeDimensionOverride=(c,m,v)=>(n._OrtAddFreeDimensionOverride=Oe.Ib)(c,m,v),n._OrtAddSessionConfigEntry=(c,m,v)=>(n._OrtAddSessionConfigEntry=Oe.Jb)(c,m,v),n._OrtReleaseSessionOptions=c=>(n._OrtReleaseSessionOptions=Oe.Kb)(c),n._OrtCreateSession=(c,m,v)=>(n._OrtCreateSession=Oe.Lb)(c,m,v),n._OrtReleaseSession=c=>(n._OrtReleaseSession=Oe.Mb)(c),n._OrtGetInputOutputCount=(c,m,v)=>(n._OrtGetInputOutputCount=Oe.Nb)(c,m,v),n._OrtGetInputName=(c,m)=>(n._OrtGetInputName=Oe.Ob)(c,m),n._OrtGetOutputName=(c,m)=>(n._OrtGetOutputName=Oe.Pb)(c,m),n._OrtFree=c=>(n._OrtFree=Oe.Qb)(c),n._OrtCreateTensor=(c,m,v,C,I,W)=>(n._OrtCreateTensor=Oe.Rb)(c,m,v,C,I,W),n._OrtGetTensorData=(c,m,v,C,I)=>(n._OrtGetTensorData=Oe.Sb)(c,m,v,C,I),n._OrtReleaseTensor=c=>(n._OrtReleaseTensor=Oe.Tb)(c),n._OrtCreateRunOptions=(c,m,v,C)=>(n._OrtCreateRunOptions=Oe.Ub)(c,m,v,C),n._OrtAddRunConfigEntry=(c,m,v)=>(n._OrtAddRunConfigEntry=Oe.Vb)(c,m,v),n._OrtReleaseRunOptions=c=>(n._OrtReleaseRunOptions=Oe.Wb)(c),n._OrtCreateBinding=c=>(n._OrtCreateBinding=Oe.Xb)(c),n._OrtBindInput=(c,m,v)=>(n._OrtBindInput=Oe.Yb)(c,m,v),n._OrtBindOutput=(c,m,v,C)=>(n._OrtBindOutput=Oe.Zb)(c,m,v,C),n._OrtClearBoundOutputs=c=>(n._OrtClearBoundOutputs=Oe._b)(c),n._OrtReleaseBinding=c=>(n._OrtReleaseBinding=Oe.$b)(c),n._OrtRunWithBinding=(c,m,v,C,I)=>(n._OrtRunWithBinding=Oe.ac)(c,m,v,C,I),n._OrtRun=(c,m,v,C,I,W,se,ge)=>(n._OrtRun=Oe.bc)(c,m,v,C,I,W,se,ge),n._OrtEndProfiling=c=>(n._OrtEndProfiling=Oe.cc)(c),n._JsepOutput=(c,m,v)=>(n._JsepOutput=Oe.dc)(c,m,v),n._JsepGetNodeName=c=>(n._JsepGetNodeName=Oe.ec)(c);var In=()=>(In=Oe.fc)(),Vr=n._free=c=>(Vr=n._free=Oe.gc)(c),on=n._malloc=c=>(on=n._malloc=Oe.ic)(c),ri=(c,m,v,C,I,W)=>(ri=Oe.kc)(c,m,v,C,I,W),uo=()=>(uo=Oe.lc)(),si=(c,m,v,C,I)=>(si=Oe.mc)(c,m,v,C,I),po=c=>(po=Oe.nc)(c),ni=c=>(ni=Oe.oc)(c),ii=(c,m)=>(ii=Oe.pc)(c,m),ho=()=>(ho=Oe.qc)(),ft=(c,m)=>(ft=Oe.rc)(c,m),Us=c=>(Us=Oe.sc)(c),mo=(c,m)=>(mo=Oe.tc)(c,m),mt=c=>(mt=Oe.uc)(c),An=c=>(An=Oe.vc)(c),_t=()=>(_t=Oe.wc)(),_o=c=>(_o=Oe.xc)(c),oi=c=>(oi=Oe.yc)(c),fo=(c,m,v)=>(fo=Oe.zc)(c,m,v),go=c=>(go=Oe.Ac)(c),ai=n.dynCall_iii=(c,m,v)=>(ai=n.dynCall_iii=Oe.Bc)(c,m,v),wo=n.dynCall_vi=(c,m)=>(wo=n.dynCall_vi=Oe.Cc)(c,m),li=n.dynCall_ii=(c,m)=>(li=n.dynCall_ii=Oe.Dc)(c,m),di=n.dynCall_vii=(c,m,v)=>(di=n.dynCall_vii=Oe.Ec)(c,m,v),yo=n.dynCall_iiii=(c,m,v,C)=>(yo=n.dynCall_iiii=Oe.Fc)(c,m,v,C),Mo=n.dynCall_viii=(c,m,v,C)=>(Mo=n.dynCall_viii=Oe.Gc)(c,m,v,C),ci=n.dynCall_iiiii=(c,m,v,C,I)=>(ci=n.dynCall_iiiii=Oe.Hc)(c,m,v,C,I),bo=n.dynCall_viiii=(c,m,v,C,I)=>(bo=n.dynCall_viiii=Oe.Ic)(c,m,v,C,I),vo=n.dynCall_viiiiii=(c,m,v,C,I,W,se)=>(vo=n.dynCall_viiiiii=Oe.Jc)(c,m,v,C,I,W,se),ui=n.dynCall_viiiiiii=(c,m,v,C,I,W,se,ge)=>(ui=n.dynCall_viiiiiii=Oe.Kc)(c,m,v,C,I,W,se,ge),xo=n.dynCall_ji=(c,m)=>(xo=n.dynCall_ji=Oe.Lc)(c,m),To=n.dynCall_v=c=>(To=n.dynCall_v=Oe.Mc)(c),pi=n.dynCall_viiiii=(c,m,v,C,I,W)=>(pi=n.dynCall_viiiii=Oe.Nc)(c,m,v,C,I,W),Eo=n.dynCall_i=c=>(Eo=n.dynCall_i=Oe.Oc)(c),Po=n.dynCall_fii=(c,m,v)=>(Po=n.dynCall_fii=Oe.Pc)(c,m,v),hi=n.dynCall_viiiiiiii=(c,m,v,C,I,W,se,ge,Ee)=>(hi=n.dynCall_viiiiiiii=Oe.Qc)(c,m,v,C,I,W,se,ge,Ee),Co=n.dynCall_viiiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze,Ye)=>(Co=n.dynCall_viiiiiiiiii=Oe.Rc)(c,m,v,C,I,W,se,ge,Ee,ze,Ye),So=n.dynCall_jiii=(c,m,v,C)=>(So=n.dynCall_jiii=Oe.Sc)(c,m,v,C),mi=n.dynCall_dii=(c,m,v)=>(mi=n.dynCall_dii=Oe.Tc)(c,m,v),$o=n.dynCall_viiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze)=>($o=n.dynCall_viiiiiiiii=Oe.Uc)(c,m,v,C,I,W,se,ge,Ee,ze),ko=n.dynCall_viiiiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot)=>(ko=n.dynCall_viiiiiiiiiii=Oe.Vc)(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot),_i=n.dynCall_iiiiii=(c,m,v,C,I,W)=>(_i=n.dynCall_iiiiii=Oe.Wc)(c,m,v,C,I,W),Io=n.dynCall_iij=(c,m,v)=>(Io=n.dynCall_iij=Oe.Xc)(c,m,v),Ao=n.dynCall_iiiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze)=>(Ao=n.dynCall_iiiiiiiiii=Oe.Yc)(c,m,v,C,I,W,se,ge,Ee,ze),Fo=n.dynCall_iiiiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze,Ye)=>(Fo=n.dynCall_iiiiiiiiiii=Oe.Zc)(c,m,v,C,I,W,se,ge,Ee,ze,Ye),Oo=n.dynCall_vij=(c,m,v)=>(Oo=n.dynCall_vij=Oe._c)(c,m,v),fi=n.dynCall_iiif=(c,m,v,C)=>(fi=n.dynCall_iiif=Oe.$c)(c,m,v,C),Do=n.dynCall_iiij=(c,m,v,C)=>(Do=n.dynCall_iiij=Oe.ad)(c,m,v,C),Lo=n.dynCall_fiii=(c,m,v,C)=>(Lo=n.dynCall_fiii=Oe.bd)(c,m,v,C),gi=n.dynCall_viiiiiiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)=>(gi=n.dynCall_viiiiiiiiiiiii=Oe.cd)(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt),zo=n.dynCall_vjiii=(c,m,v,C,I)=>(zo=n.dynCall_vjiii=Oe.dd)(c,m,v,C,I),Bo=n.dynCall_vif=(c,m,v)=>(Bo=n.dynCall_vif=Oe.ed)(c,m,v),wi=n.dynCall_iiiiiii=(c,m,v,C,I,W,se)=>(wi=n.dynCall_iiiiiii=Oe.fd)(c,m,v,C,I,W,se),Ro=n.dynCall_iiiij=(c,m,v,C,I)=>(Ro=n.dynCall_iiiij=Oe.gd)(c,m,v,C,I),No=n.dynCall_iiiiiiii=(c,m,v,C,I,W,se,ge)=>(No=n.dynCall_iiiiiiii=Oe.hd)(c,m,v,C,I,W,se,ge),yi=n.dynCall_viiiiiiiiiiii=(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt)=>(yi=n.dynCall_viiiiiiiiiiii=Oe.id)(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt),jo=n.dynCall_diii=(c,m,v,C)=>(jo=n.dynCall_diii=Oe.jd)(c,m,v,C),Uo=n.dynCall_jiiii=(c,m,v,C,I)=>(Uo=n.dynCall_jiiii=Oe.kd)(c,m,v,C,I),Mi=n.dynCall_viiij=(c,m,v,C,I)=>(Mi=n.dynCall_viiij=Oe.ld)(c,m,v,C,I),Vo=n.dynCall_fiiii=(c,m,v,C,I)=>(Vo=n.dynCall_fiiii=Oe.md)(c,m,v,C,I),Wo=n.dynCall_viiif=(c,m,v,C,I)=>(Wo=n.dynCall_viiif=Oe.nd)(c,m,v,C,I),bi=n.dynCall_diiii=(c,m,v,C,I)=>(bi=n.dynCall_diiii=Oe.od)(c,m,v,C,I),Go=n.dynCall_viiid=(c,m,v,C,I)=>(Go=n.dynCall_viiid=Oe.pd)(c,m,v,C,I),Ko=n.dynCall_iiiijii=(c,m,v,C,I,W,se)=>(Ko=n.dynCall_iiiijii=Oe.qd)(c,m,v,C,I,W,se),vi=n.dynCall_iiiiiij=(c,m,v,C,I,W,se)=>(vi=n.dynCall_iiiiiij=Oe.rd)(c,m,v,C,I,W,se),Ho=c=>(Ho=Oe.sd)(c),qo=()=>(qo=Oe.td)(),Qo=c=>(Qo=Oe.ud)(c),Xo=()=>(Xo=Oe.vd)();function Jo(c,m,v){var C=_t();try{di(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function dl(c,m,v){var C=_t();try{return ai(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function cl(c,m){var v=_t();try{wo(c,m)}catch(C){if(mt(v),C!==C+0)throw C;ft(1,0)}}function ul(c,m){var v=_t();try{return li(c,m)}catch(C){if(mt(v),C!==C+0)throw C;ft(1,0)}}function pl(c,m,v,C){var I=_t();try{return yo(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;ft(1,0)}}function Yo(c,m,v,C,I){var W=_t();try{bo(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function hl(c,m,v,C,I){var W=_t();try{return ci(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function ml(c,m,v,C){var I=_t();try{Mo(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;ft(1,0)}}function _l(c,m,v,C,I,W,se){var ge=_t();try{return wi(c,m,v,C,I,W,se)}catch(Ee){if(mt(ge),Ee!==Ee+0)throw Ee;ft(1,0)}}function fl(c){var m=_t();try{To(c)}catch(v){if(mt(m),v!==v+0)throw v;ft(1,0)}}function Zo(c,m,v){var C=_t();try{return Io(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function gl(c,m,v,C,I,W){var se=_t();try{pi(c,m,v,C,I,W)}catch(ge){if(mt(se),ge!==ge+0)throw ge;ft(1,0)}}function wl(c,m,v){var C=_t();try{Oo(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function yl(c,m,v,C,I,W,se){var ge=_t();try{vo(c,m,v,C,I,W,se)}catch(Ee){if(mt(ge),Ee!==Ee+0)throw Ee;ft(1,0)}}function Ml(c,m,v,C,I,W,se,ge){var Ee=_t();try{ui(c,m,v,C,I,W,se,ge)}catch(ze){if(mt(Ee),ze!==ze+0)throw ze;ft(1,0)}}function ea(c,m,v,C,I,W){var se=_t();try{return _i(c,m,v,C,I,W)}catch(ge){if(mt(se),ge!==ge+0)throw ge;ft(1,0)}}function bl(c,m,v,C,I,W,se,ge){var Ee=_t();try{return No(c,m,v,C,I,W,se,ge)}catch(ze){if(mt(Ee),ze!==ze+0)throw ze;ft(1,0)}}function vl(c,m,v,C,I,W,se,ge,Ee,ze){var Ye=_t();try{$o(c,m,v,C,I,W,se,ge,Ee,ze)}catch(ot){if(mt(Ye),ot!==ot+0)throw ot;ft(1,0)}}function ta(c,m,v,C,I,W,se,ge,Ee){var ze=_t();try{hi(c,m,v,C,I,W,se,ge,Ee)}catch(Ye){if(mt(ze),Ye!==Ye+0)throw Ye;ft(1,0)}}function xl(c){var m=_t();try{return Eo(c)}catch(v){if(mt(m),v!==v+0)throw v;ft(1,0)}}function Tl(c,m,v,C,I,W,se,ge,Ee,ze){var Ye=_t();try{return Ao(c,m,v,C,I,W,se,ge,Ee,ze)}catch(ot){if(mt(Ye),ot!==ot+0)throw ot;ft(1,0)}}function ra(c,m,v){var C=_t();try{return Po(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function El(c,m,v,C){var I=_t();try{return So(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;return ft(1,0),0n}}function Pl(c,m,v){var C=_t();try{return mi(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function sa(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot){var gt=_t();try{ko(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot)}catch(Bt){if(mt(gt),Bt!==Bt+0)throw Bt;ft(1,0)}}function Cl(c,m,v,C,I,W,se,ge,Ee,ze,Ye){var ot=_t();try{Co(c,m,v,C,I,W,se,ge,Ee,ze,Ye)}catch(gt){if(mt(ot),gt!==gt+0)throw gt;ft(1,0)}}function Sl(c,m,v,C,I,W,se,ge,Ee,ze,Ye){var ot=_t();try{return Fo(c,m,v,C,I,W,se,ge,Ee,ze,Ye)}catch(gt){if(mt(ot),gt!==gt+0)throw gt;ft(1,0)}}function na(c,m,v,C){var I=_t();try{return fi(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;ft(1,0)}}function $l(c,m,v,C){var I=_t();try{return Do(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;ft(1,0)}}function kl(c,m,v,C){var I=_t();try{return Lo(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;ft(1,0)}}function xi(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt){var Pr=_t();try{gi(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt,Bt)}catch(an){if(mt(Pr),an!==an+0)throw an;ft(1,0)}}function Il(c,m,v,C,I){var W=_t();try{zo(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function Al(c,m,v){var C=_t();try{Bo(c,m,v)}catch(I){if(mt(C),I!==I+0)throw I;ft(1,0)}}function ia(c,m){var v=_t();try{return xo(c,m)}catch(C){if(mt(v),C!==C+0)throw C;return ft(1,0),0n}}function oa(c,m,v,C,I){var W=_t();try{return Ro(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function Fl(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt){var Bt=_t();try{yi(c,m,v,C,I,W,se,ge,Ee,ze,Ye,ot,gt)}catch(Pr){if(mt(Bt),Pr!==Pr+0)throw Pr;ft(1,0)}}function aa(c,m,v,C){var I=_t();try{return jo(c,m,v,C)}catch(W){if(mt(I),W!==W+0)throw W;ft(1,0)}}function Ol(c,m,v,C,I){var W=_t();try{return Uo(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;return ft(1,0),0n}}function Dl(c,m,v,C,I){var W=_t();try{Mi(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function Ll(c,m,v,C,I){var W=_t();try{return Vo(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function la(c,m,v,C,I){var W=_t();try{Wo(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function zl(c,m,v,C,I){var W=_t();try{return bi(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function Bl(c,m,v,C,I){var W=_t();try{Go(c,m,v,C,I)}catch(se){if(mt(W),se!==se+0)throw se;ft(1,0)}}function Rl(c,m,v,C,I,W,se){var ge=_t();try{return Ko(c,m,v,C,I,W,se)}catch(Ee){if(mt(ge),Ee!==Ee+0)throw Ee;ft(1,0)}}function da(c,m,v,C,I,W,se){var ge=_t();try{return vi(c,m,v,C,I,W,se)}catch(Ee){if(mt(ge),Ee!==Ee+0)throw Ee;ft(1,0)}}return n.stackSave=()=>_t(),n.stackRestore=c=>mt(c),n.stackAlloc=c=>An(c),n.setValue=function(c,m,v="i8"){switch(v.endsWith("*")&&(v="*"),v){case"i1":case"i8":R()[c>>>0]=m;break;case"i16":G()[c>>>1>>>0]=m;break;case"i32":X()[c>>>2>>>0]=m;break;case"i64":H[c>>>3]=BigInt(m);break;case"float":_e()[c>>>2>>>0]=m;break;case"double":ke()[c>>>3>>>0]=m;break;case"*":ye()[c>>>2>>>0]=m;break;default:Ie(`invalid type for setValue: ${v}`)}},n.getValue=function(c,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return R()[c>>>0];case"i16":return G()[c>>>1>>>0];case"i32":return X()[c>>>2>>>0];case"i64":return H[c>>>3];case"float":return _e()[c>>>2>>>0];case"double":return ke()[c>>>3>>>0];case"*":return ye()[c>>>2>>>0];default:Ie(`invalid type for getValue: ${m}`)}},n.UTF8ToString=zt,n.stringToUTF8=Er,n.lengthBytesUTF8=hs,function c(){if(0{fd(),bd=typeof location>"u"?void 0:location.origin,vd=self.location.href>"file:"&&self.location.href<"file;",op=()=>{{if(vd){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,bd).href}return self.location.href}},Rr=op(),ap=()=>{if(Rr&&!Rr.startsWith("blob:"))return Rr.substring(0,Rr.lastIndexOf("/")+1)},fa=(e,r)=>{try{let t=r??Rr;return(t?new URL(e,t):new URL(e)).origin===bd}catch{return!1}},lp=(e,r)=>{let t=r??Rr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},dp=(e,r)=>`${r??"./"}${e}`,xd=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},cp=async e=>(await import(e)).default,Td=(Zb(),ma(tp)).default,up=async()=>{if(!Rr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(fa(Rr))return[void 0,Td()];let e=await xd(Rr);return[e,Td(e)]},Ed=(ev(),ma(sp)).default,pp=async(e,r,t)=>{if(!e&&!r&&Ed&&Rr&&fa(Rr))return[void 0,Ed];{let s="ort-wasm-simd-threaded.jsep.mjs",i=e??lp(s,r),n=t&&i&&!fa(i,r),o=n?await xd(i):i??dp(s,r);return[n?o:void 0,await cp(o)]}}}),Cd,ga,Ii,Sd,hp,mp,$d,ar,hn=Ue(()=>{Pd(),ga=!1,Ii=!1,Sd=!1,hp=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},mp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},$d=async e=>{if(ga)return Promise.resolve();if(Ii)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Sd)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ii=!0;let r=e.initTimeout,t=e.numThreads;if(!mp())throw new Error("WebAssembly SIMD is not supported in the current environment.");let s=hp();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let i=e.wasmPaths,n=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,a=(o==null?void 0:o.href)??o,l=i==null?void 0:i.wasm,d=(l==null?void 0:l.href)??l,p=e.wasmBinary,[u,h]=await pp(a,n,t>1),w=!1,f=[];if(r>0&&f.push(new Promise(P=>{setTimeout(()=>{w=!0,P()},r)})),f.push(new Promise((P,A)=>{let b={numThreads:t};if(p)b.wasmBinary=p;else if(d||n)b.locateFile=y=>d??n+y;else if(a&&a.indexOf("blob:")!==0)b.locateFile=y=>new URL(y,a).href;else if(u){let y=ap();y&&(b.locateFile=$=>y+$)}h(b).then(y=>{Ii=!1,ga=!0,Cd=y,P(),u&&URL.revokeObjectURL(u)},y=>{Ii=!1,Sd=!0,A(y)})})),await Promise.race(f),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},ar=()=>{if(ga&&Cd)return Cd;throw new Error("WebAssembly is not initialized yet.")}}),Mr,wa,At,kd=Ue(()=>{hn(),Mr=(e,r)=>{let t=ar(),s=t.lengthBytesUTF8(e)+1,i=t._malloc(s);return t.stringToUTF8(e,i,s),r.push(i),i},wa=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([i,n])=>{let o=r?r+i:i;if(typeof n=="object")wa(n,o+".",t,s);else if(typeof n=="string"||typeof n=="number")s(o,n.toString());else if(typeof n=="boolean")s(o,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},At=e=>{let r=ar(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetLastError(i,i+s);let n=Number(r.getValue(i,s===4?"i32":"i64")),o=r.getValue(i+s,"*"),a=o?r.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),_p,tv=Ue(()=>{hn(),kd(),_p=e=>{let r=ar(),t=0,s=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=Mr(e.tag,s)),t=r._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&wa(e.extra,"",new WeakSet,(o,a)=>{let l=Mr(o,s),d=Mr(a,s);r._OrtAddRunConfigEntry(t,l,d)!==0&&At(`Can't set a run config entry: ${o} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(o=>r._free(o)),n}}}),fp,gp,wp,yp,Mp,rv=Ue(()=>{hn(),kd(),fp=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},gp=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},wp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},yp=(e,r,t)=>{for(let s of r){let i=typeof s=="string"?s:s.name;switch(i){case"webnn":if(i="WEBNN",typeof s!="string"){let o=s==null?void 0:s.deviceType;if(o){let a=Mr("deviceType",t),l=Mr(o,t);ar()._OrtAddSessionConfigEntry(e,a,l)!==0&&At(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof s!="string"){let o=s;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let a=Mr("preferredLayout",t),l=Mr(o.preferredLayout,t);ar()._OrtAddSessionConfigEntry(e,a,l)!==0&&At(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let n=Mr(i,t);ar()._OrtAppendExecutionProvider(e,n)!==0&&At(`Can't append execution provider: ${i}.`)}},Mp=e=>{let r=ar(),t=0,s=[],i=e||{};wp(i);try{let n=fp(i.graphOptimizationLevel??"all"),o=gp(i.executionMode??"sequential"),a=typeof i.logId=="string"?Mr(i.logId,s):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let d=i.logVerbosityLevel??0;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log verbosity level is not valid: ${d}`);let p=typeof i.optimizedModelFilePath=="string"?Mr(i.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,a,l,d,p),t===0&&At("Can't create session options."),i.executionProviders&&yp(t,i.executionProviders,s),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let u=Mr("enableGraphCapture",s),h=Mr(i.enableGraphCapture.toString(),s);r._OrtAddSessionConfigEntry(t,u,h)!==0&&At(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[u,h]of Object.entries(i.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let w=Mr(u,s);r._OrtAddFreeDimensionOverride(t,w,h)!==0&&At(`Can't set a free dimension override: ${u} - ${h}.`)}return i.extra!==void 0&&wa(i.extra,"",new WeakSet,(u,h)=>{let w=Mr(u,s),f=Mr(h,s);r._OrtAddSessionConfigEntry(t,w,f)!==0&&At(`Can't set a session config entry: ${u} - ${h}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(o=>r._free(o)),n}}}),Rn,mn,_n,Id,ya,Ad,Fd,Od,pt=Ue(()=>{Rn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},mn=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},_n=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((i,n)=>i*n,1);return t>0?Math.ceil(s*t):void 0},Id=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},ya=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Ad=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Fd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Od=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Dd,bp=Ue(()=>{fd(),Dd=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let o=0;for(;;){let{done:a,value:l}=await i.read();if(a)break;let d=l.byteLength;new Uint8Array(n,o,d).set(l),o+=d}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),vp,xp,Tp,Ep,Ld,Pp,St,ks=Ue(()=>{pt(),vp=["V","I","W","E","F"],xp=(e,r)=>{console.log(`[${vp[e]},${new Date().toISOString()}]${r}`)},Ld=(e,r)=>{Tp=e,Ep=r},Pp=(e,r)=>{let t=ya(e),s=ya(Tp);t>=s&&xp(t,typeof r=="function"?r():r)},St=(...e)=>{Ep&&Pp(...e)}}),zd,Cp=Ue(()=>{pt(),zd=(e,r)=>new(Id(r))(e)}),Bd=Ue(()=>{}),Rd,Ma,ba,Sp,$p,Nd,jd,kp,Ip,sv=Ue(()=>{ks(),Bd(),Rd=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ma=[],ba=e=>Math.ceil(Number(e)/16)*16,Sp=e=>{for(let r=0;r$p++,jd=async(e,r,t,s)=>{let i=ba(t),n=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(r,0,n,0,i),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},kp=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of Rd)Ma.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,i=r.byteLength,n=ba(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,i)),a.unmap();let d=this.backend.device.createCommandEncoder();d.copyBufferToBuffer(a,0,o.gpuData.buffer,0,n),this.backend.device.queue.submit([d.finish()]),a.destroy(),St("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=ba(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,i)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else s=Nd();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),St("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Sp(e),s,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||n){let a=(i?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let o={id:Nd(),type:0,buffer:s};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),St("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return St("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await jd(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=Rd.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(St("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Ip=(...e)=>new kp(...e)}),Ap,Dt,Yt=Ue(()=>{Ap=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Dt=e=>new Ap(e)}),Fp,Nn,xe,va,Op,Dp,Lp,Mt=Ue(()=>{Fp=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Nn=class{static calcShape(e,r,t=!1){let s=e.length,i=r.length;if(s===0)return r;if(i===0)return e;let n=Math.max(e.length,r.length),o=new Array(n);if(t){if(s<2||i<2)return;let a=Fp.calcMatMulShape([e[s-2],e[s-1]],[r[i-2],r[i-1]]);if(a===void 0)return;[o[n-2],o[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],d=i-a<0?1:r[i-a];if(l!==d&&l>1&&d>1)return;let p=Math.max(l,d);if(l&&d)o[n-a]=Math.max(l,d);else{if(p>1)return;o[n-a]=0}}return o}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let i=1;i<=t;i++)if(e[t-i]!==1&&e[t-i]!==r[s-i])return!1;return!0}},xe=class od{static size(r){return od.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let i=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){i[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");i[n]=1,t/=r[n],n--}for(n--;n>=0;n--)i[n]=r[n];return i}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return od.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return od.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let i=1;for(let n=t;n=0;--i)s[i]=s[i+1]*r[i+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((i,n)=>i+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,i)=>s===t[i])}},va=class pa{static adjustPoolAttributes(r,t,s,i,n,o){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||o[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,i,n,o,a){if(a){if(n.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{pt(),Mt(),jn=64,xa=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},lr=(e,r=1)=>{let t=xa(e,r);return typeof t=="string"?t:t[0]},Tr=(e,r=1)=>{let t=xa(e,r);return typeof t=="string"?t:t[1]},nt=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:xe.computeStrides(t)})}),r},Xt=e=>e%4===0?4:e%2===0?2:1,Ud=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Un=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ws=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,rt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,Ai=(e,r,t,s,i)=>{let n=typeof t=="number",o=n?t:t.length,a=[...new Array(o).keys()],l=o<2?"u32":o<=4?`vec${o}`:`array`,d=xa(r,i),p=typeof d=="string"?d:d[1],u=typeof d=="string"?d:d[0],h={indices:l,value:p,storage:u,tensor:r},w=R=>typeof R=="string"?R:`${R}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},P=n?"uniforms.":"",A=`${P}${e}_shape`,b=`${P}${e}_strides`,y="";for(let R=0;R ${h.indices} { var indices: ${h.indices}; var current = offset; ${y} return indices; - }`,x=N=>(_.offsetToIndices=!0,o<2?N:`o2i_${e}(${N})`),g=[];if(o>=2)for(let N=o-1;N>=0;N--)g.push(`${rt(v,N,o)} * (indices[${N}])`);let M=o<2?"":` + }`,T=R=>(f.offsetToIndices=!0,o<2?R:`o2i_${e}(${R})`),g=[];if(o>=2)for(let R=o-1;R>=0;R--)g.push(`${rt(b,R,o)} * (indices[${R}])`);let M=o<2?"":` fn i2o_${e}(indices: ${h.indices}) -> u32 { return ${g.join("+")}; - }`,E=N=>(_.indicesToOffset=!0,o<2?N:`i2o_${e}(${N})`),k=(...N)=>o===0?"0u":`${h.indices}(${N.map(w).join(",")})`,B=(N,O)=>o<2?`${N}`:`${rt(N,O,o)}`,R=(N,O,G)=>o<2?`${N}=${G};`:`${rt(N,O,o)}=${G};`,J={},q=(N,O)=>{_.broadcastedIndicesToOffset=!0;let G=`${O.name}broadcastedIndicesTo${e}Offset`;if(G in J)return`${G}(${N})`;let ne=[];for(let X=o-1;X>=0;X--){let we=O.indicesGet("outputIndices",X+O.rank-o);ne.push(`${B(v,X)} * (${we} % ${B(A,X)})`)}return J[G]=`fn ${G}(outputIndices: ${O.type.indices}) -> u32 { + }`,E=R=>(f.indicesToOffset=!0,o<2?R:`i2o_${e}(${R})`),k=(...R)=>o===0?"0u":`${h.indices}(${R.map(w).join(",")})`,B=(R,O)=>o<2?`${R}`:`${rt(R,O,o)}`,N=(R,O,G)=>o<2?`${R}=${G};`:`${rt(R,O,o)}=${G};`,J={},q=(R,O)=>{f.broadcastedIndicesToOffset=!0;let G=`${O.name}broadcastedIndicesTo${e}Offset`;if(G in J)return`${G}(${R})`;let ne=[];for(let X=o-1;X>=0;X--){let ye=O.indicesGet("outputIndices",X+O.rank-o);ne.push(`${B(b,X)} * (${ye} % ${B(A,X)})`)}return J[G]=`fn ${G}(outputIndices: ${O.type.indices}) -> u32 { return ${ne.length>0?ne.join("+"):"0u"}; - }`,`${G}(${N})`},V=(N,O)=>(()=>{if(h.storage===h.value)return`${e}[${N}]=${O};`;if(h.storage==="vec2"&&h.value==="i32")return`${e}[${N}]=vec2(u32(${O}), select(0u, 0xFFFFFFFFu, ${O} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${e}[${N}]=vec2(u32(${O}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${O}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Y=N=>(()=>{if(h.storage===h.value)return`${e}[${N}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${e}[${N}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${e}[${N}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),H=o<2?"":` + }`,`${G}(${R})`},V=(R,O)=>(()=>{if(h.storage===h.value)return`${e}[${R}]=${O};`;if(h.storage==="vec2"&&h.value==="i32")return`${e}[${R}]=vec2(u32(${O}), select(0u, 0xFFFFFFFFu, ${O} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${e}[${R}]=vec2(u32(${O}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${e}[${R}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${O}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Y=R=>(()=>{if(h.storage===h.value)return`${e}[${R}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${e}[${R}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${e}[${R}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${e}[${R}] & 0xFFu), bool(${e}[${R}] & 0xFF00u), bool(${e}[${R}] & 0xFF0000u), bool(${e}[${R}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),H=o<2?"":` fn get_${e}ByIndices(indices: ${h.indices}) -> ${p} { return ${Y(`i2o_${e}(indices)`)}; - }`,Q=o<2?"":(()=>{let N=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` - fn get_${e}(${N}) -> ${p} { + }`,Q=o<2?"":(()=>{let R=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` + fn get_${e}(${R}) -> ${p} { return get_${e}ByIndices(${k(O)}); - }`})(),ie=(...N)=>{if(N.length!==o)throw new Error(`indices length must be ${o}`);let O=N.map(w).join(",");return o===0?Y("0u"):o===1?Y(O[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${O})`)},le=N=>o<2?Y(N):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ae=o<2?"":` + }`})(),ie=(...R)=>{if(R.length!==o)throw new Error(`indices length must be ${o}`);let O=R.map(w).join(",");return o===0?Y("0u"):o===1?Y(O[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${O})`)},le=R=>o<2?Y(R):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${R})`),ae=o<2?"":` fn set_${e}ByIndices(indices: ${h.indices}, value: ${p}) { ${V(`i2o_${e}(indices)`,"value")} - }`,ge=o<2?"":(()=>{let N=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` - fn set_${e}(${N}, value: ${p}) { + }`,we=o<2?"":(()=>{let R=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` + fn set_${e}(${R}, value: ${p}) { set_${e}ByIndices(${k(O)}, value); - }`})();return{impl:()=>{let N=[],O=!1;return _.offsetToIndices&&(N.push(S),O=!0),_.indicesToOffset&&(N.push(M),O=!0),_.broadcastedIndicesToOffset&&(Object.values(J).forEach(G=>N.push(G)),O=!0),_.set&&(N.push(ge),O=!0),_.setByIndices&&(N.push(ae),O=!0),_.get&&(N.push(Q),O=!0),_.getByIndices&&(N.push(H),O=!0),!n&&O&&N.unshift(`const ${A} = ${h.indices}(${t.join(",")});`,`const ${v} = ${h.indices}(${xe.computeStrides(t).join(",")});`),N.join(` -`)},type:h,offsetToIndices:x,indicesToOffset:E,broadcastedIndicesToOffset:q,indices:k,indicesGet:B,indicesSet:R,set:(...N)=>{if(N.length!==o+1)throw new Error(`indices length must be ${o}`);let O=N[o];if(typeof O!="string")throw new Error("value must be string");let G=N.slice(0,o).map(w).join(",");return o===0?V("0u",O):o===1?V(G[0],O):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${G}, ${O})`)},setByOffset:V,setByIndices:(N,O)=>o<2?V(N,O):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${O});`),get:ie,getByOffset:Y,getByIndices:le,usage:s,name:e,strides:v,shape:A,rank:o}},$e=(e,r,t,s=1)=>Ai(e,r,t,"input",s),tt=(e,r,t,s=1)=>Ai(e,r,t,"output",s),Lp=(e,r,t)=>Ai(e,r,t,"atomicOutput",1),Ud=(e,r,t,s=1)=>Ai(e,r,t,"internal",s),zp=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=jn){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=i?`@builtin(global_invocation_id) global_id : vec3, + }`})();return{impl:()=>{let R=[],O=!1;return f.offsetToIndices&&(R.push($),O=!0),f.indicesToOffset&&(R.push(M),O=!0),f.broadcastedIndicesToOffset&&(Object.values(J).forEach(G=>R.push(G)),O=!0),f.set&&(R.push(we),O=!0),f.setByIndices&&(R.push(ae),O=!0),f.get&&(R.push(Q),O=!0),f.getByIndices&&(R.push(H),O=!0),!n&&O&&R.unshift(`const ${A} = ${h.indices}(${t.join(",")});`,`const ${b} = ${h.indices}(${xe.computeStrides(t).join(",")});`),R.join(` +`)},type:h,offsetToIndices:T,indicesToOffset:E,broadcastedIndicesToOffset:q,indices:k,indicesGet:B,indicesSet:N,set:(...R)=>{if(R.length!==o+1)throw new Error(`indices length must be ${o}`);let O=R[o];if(typeof O!="string")throw new Error("value must be string");let G=R.slice(0,o).map(w).join(",");return o===0?V("0u",O):o===1?V(G[0],O):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${G}, ${O})`)},setByOffset:V,setByIndices:(R,O)=>o<2?V(R,O):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${R}, ${O});`),get:ie,getByOffset:Y,getByIndices:le,usage:s,name:e,strides:b,shape:A,rank:o}},$e=(e,r,t,s=1)=>Ai(e,r,t,"input",s),tt=(e,r,t,s=1)=>Ai(e,r,t,"output",s),zp=(e,r,t)=>Ai(e,r,t,"atomicOutput",1),Vd=(e,r,t,s=1)=>Ai(e,r,t,"internal",s),Bp=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=jn){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @@ -58,46 +58,46 @@ var bx=Object.defineProperty;var vx=(bs,Sr,Ln)=>Sr in bs?bx(bs,Sr,{enumerable:!0 struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` -`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Bp=(e,r)=>new zp(e,r)}),Rp,Vd,Np,jp,Up,Vp,Nr,Wp,Gp,Gs=je(()=>{pt(),yt(),Yt(),vt(),Rp=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},Vd=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Np=(e,r)=>xe.sortBasedOnPerm(e,Vd(e.length,r)),jp=(e,r,t,s)=>{let i=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { - var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let i=0;i{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,i=Vd(s,r),n=Np(e.dims,i),o=e.dims,a=n,l=s<2||Vp(i,e.dims),d;if(l)return d=_=>{let P=$e("input",t,o,4),A=tt("output",t,a,4);return` - ${_.registerUniform("output_size","u32").declareVariables(P,A)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Rp=(e,r)=>new Bp(e,r)}),Np,Wd,jp,Up,Vp,Wp,Nr,Gp,Kp,Gs=Ue(()=>{pt(),Mt(),Yt(),xt(),Np=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},Wd=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),jp=(e,r)=>xe.sortBasedOnPerm(e,Wd(e.length,r)),Up=(e,r,t,s)=>{let i=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let i=0;i{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,i=Wd(s,r),n=jp(e.dims,i),o=e.dims,a=n,l=s<2||Wp(i,e.dims),d;if(l)return d=f=>{let P=$e("input",t,o,4),A=tt("output",t,a,4);return` + ${f.registerUniform("output_size","u32").declareVariables(P,A)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:d};let{newShape:p,newPerm:u}=Up(e.dims,i),h=xe.areEqual(u,[2,3,1]),w=xe.areEqual(u,[3,1,2]);if(p.length===2||h||w){o=h?[p[0],p[1]*p[2]]:w?[p[0]*p[1],p[2]]:p,a=[o[1],o[0]];let _=16;return d=P=>{let A=$e("a",t,o.length),v=tt("output",t,a.length);return` - ${P.registerUniform("output_size","u32").declareVariables(A,v)} - var tile : array, ${_}>; - ${P.mainStart([_,_,1])} - let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let f=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64/4)},programUniforms:[{type:12,data:Math.ceil(f/4)}]}},getShaderSource:d};let{newShape:p,newPerm:u}=Vp(e.dims,i),h=xe.areEqual(u,[2,3,1]),w=xe.areEqual(u,[3,1,2]);if(p.length===2||h||w){o=h?[p[0],p[1]*p[2]]:w?[p[0]*p[1],p[2]]:p,a=[o[1],o[0]];let f=16;return d=P=>{let A=$e("a",t,o.length),b=tt("output",t,a.length);return` + ${P.registerUniform("output_size","u32").declareVariables(A,b)} + var tile : array, ${f}>; + ${P.mainStart([f,f,1])} + let stride = (uniforms.output_shape[1] - 1) / ${f} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; - let input_col = workgroup_id_y * ${_}u + local_id.x; - let input_row = workgroup_id_x * ${_}u + local_id.y; + let input_col = workgroup_id_y * ${f}u + local_id.x; + let input_row = workgroup_id_x * ${f}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${A.getByIndices(`${A.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); - let output_col = workgroup_id_x * ${_}u + local_id.x; - let output_row = workgroup_id_y * ${_}u + local_id.y; + let output_col = workgroup_id_x * ${f}u + local_id.x; + let output_row = workgroup_id_y * ${f}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { - ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + ${b.setByIndices(`${b.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } - }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let P=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:P},...nt(o,a)]}},getShaderSource:d}}return d=_=>{let P=$e("a",t,o.length),A=tt("output",t,a.length);return` - ${_.registerUniform("output_size","u32").declareVariables(P,A)} + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let P=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/f),y:Math.ceil(a[0]/f)},programUniforms:[{type:12,data:P},...nt(o,a)]}},getShaderSource:d}}return d=f=>{let P=$e("a",t,o.length),A=tt("output",t,a.length);return` + ${f.registerUniform("output_size","u32").declareVariables(P,A)} - ${jp(i,s,P,A)} + ${Up(i,s,P,A)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${A.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${A.setByOffset("global_idx",P.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...nt(o,a)]}},getShaderSource:d}},Wp=(e,r)=>{Rp(e.inputs,r.perm),e.compute(Nr(e.inputs[0],r.perm))},Gp=e=>Dt({perm:e.perm})}),Kp,Hp,qp,Qp,Xp,Jp,Yp,Zp,eh,th,ns,rh,sh,nh,ih,oh,ah,lh,dh,ch,uh,Hb=je(()=>{pt(),yt(),vt(),Gd(),Gs(),Kp={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Hp={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},qp={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Qp={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Xp=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,i]},Yp=(e,r)=>{let t=e.length+r.length,s=[],i=0;for(let n=0;n{for(let t=0;t{let t=[];if(!Zp(e,r)){for(let s=0;st.push(s))}return t},th=(e,r,t,s,i,n,o)=>{let a=t[0].dims,l=xe.size(n),d=xe.size(o),p=$e("_A",t[0].dataType,a),u=tt("output",i,n),h=64;l===1&&(h=256);let w=` + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let f=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...nt(o,a)]}},getShaderSource:d}},Gp=(e,r)=>{Np(e.inputs,r.perm),e.compute(Nr(e.inputs[0],r.perm))},Kp=e=>Dt({perm:e.perm})}),Hp,qp,Qp,Xp,Jp,Yp,Zp,eh,th,rh,ns,sh,nh,ih,oh,ah,lh,dh,ch,uh,ph,nv=Ue(()=>{pt(),Mt(),xt(),Kd(),Gs(),Hp={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},qp={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Qp={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Xp={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Jp=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,i]},Zp=(e,r)=>{let t=e.length+r.length,s=[],i=0;for(let n=0;n{for(let t=0;t{let t=[];if(!eh(e,r)){for(let s=0;st.push(s))}return t},rh=(e,r,t,s,i,n,o)=>{let a=t[0].dims,l=xe.size(n),d=xe.size(o),p=$e("_A",t[0].dataType,a),u=tt("output",i,n),h=64;l===1&&(h=256);let w=` var aBestValues : array; - `,_=P=>` + `,f=P=>` ${P.registerUniform("reduceSize","u32").declareVariables(p,u)} ${w} fn DIV_CEIL(a : u32, b : u32) -> u32 { @@ -108,11 +108,11 @@ var bx=Object.defineProperty;var vx=(bs,Sr,Ln)=>Sr in bs?bx(bs,Sr,{enumerable:!0 let outputIndex = global_idx / ${h}; let offset = outputIndex * uniforms.reduceSize; - var bestValue = f32(${qp[s]}); + var bestValue = f32(${Qp[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${h}) { let candidate = f32(${p.getByOffset("offset + k")}); - bestValue = ${Kp[s]}; + bestValue = ${Hp[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); @@ -123,7 +123,7 @@ var bx=Object.defineProperty;var vx=(bs,Sr,Ln)=>Sr in bs?bx(bs,Sr,{enumerable:!0 let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; - bestValue = ${Hp[s]}; + bestValue = ${qp[s]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; @@ -131,42 +131,42 @@ var bx=Object.defineProperty;var vx=(bs,Sr,Ln)=>Sr in bs?bx(bs,Sr,{enumerable:!0 } if (local_idx == 0u) { - ${u.setByOffset("outputIndex",`${s==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${Qp[s]})`}`)}; + ${u.setByOffset("outputIndex",`${s==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${Xp[s]})`}`)}; } - }`;return{name:e,shaderCache:{hint:`${r};${h}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:d}]})}},ns=(e,r,t,s)=>{let i=e.inputs.length===1?t:Wd(e.inputs,t),n=i.axes;n.length===0&&!i.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((w,_)=>_));let o=xe.normalizeAxes(n,e.inputs[0].dims.length),a=o,l=e.inputs[0],d=eh(a,e.inputs[0].dims.length);d.length>0&&(l=e.compute(Nr(e.inputs[0],d),{inputs:[0],outputs:[-1]})[0],a=Xp(a.length,l.dims.length));let[p,u]=Jp(l.dims,a),h=p;i.keepDims&&(h=Yp(p,o)),e.compute(th(r,i.cacheKey,[l],s,e.inputs[0].dataType,h,u),{inputs:[l]})},rh=(e,r)=>{ns(e,"ReduceMeanShared",r,"mean")},sh=(e,r)=>{ns(e,"ReduceL1Shared",r,"l1")},nh=(e,r)=>{ns(e,"ReduceL2Shared",r,"l2")},ih=(e,r)=>{ns(e,"ReduceLogSumExpShared",r,"logSumExp")},oh=(e,r)=>{ns(e,"ReduceMaxShared",r,"max")},ah=(e,r)=>{ns(e,"ReduceMinShared",r,"min")},lh=(e,r)=>{ns(e,"ReduceProdShared",r,"prod")},dh=(e,r)=>{ns(e,"ReduceSumShared",r,"sum")},ch=(e,r)=>{ns(e,"ReduceSumSquareShared",r,"sumSquare")},uh=(e,r)=>{ns(e,"ReduceLogSumShared",r,"logSum")}}),is,ph,Ta,Wd,os,hh,mh,fh,_h,gh,wh,yh,Mh,bh,vh,as,xh,Th,Eh,Ph,Ch,Sh,$h,kh,Ih,Ah,Gd=je(()=>{pt(),yt(),Yt(),vt(),Hb(),is=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},ph=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Ta=(e,r,t,s,i,n,o=!1,a=!1)=>{let l=[],d=t[0].dims,p=d.length,u=xe.normalizeAxes(i,p),h=!a&&u.length===0;d.forEach((P,A)=>{h||u.indexOf(A)>=0?o&&l.push(1):l.push(P)});let w=l.length,_=xe.size(l);return{name:e,shaderCache:r,getShaderSource:P=>{let A=[],v=$e("_A",t[0].dataType,p),y=tt("output",n,w),S=s(v,y,u),x=S[2];for(let g=0,M=0;g=0?(o&&M++,x=`for(var j${g}: u32 = 0; j${g} < ${d[g]}; j${g}++) { - ${S[2].includes("last_index")?`let last_index = j${g};`:""} - ${v.indicesSet("input_indices",g,`j${g}`)} - ${x} - }`):(A.push(`${v.indicesSet("input_indices",g,y.indicesGet("output_indices",M))};`),M++);return` + }`;return{name:e,shaderCache:{hint:`${r};${h}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:d}]})}},ns=(e,r,t,s)=>{let i=e.inputs.length===1?t:Gd(e.inputs,t),n=i.axes;n.length===0&&!i.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((w,f)=>f));let o=xe.normalizeAxes(n,e.inputs[0].dims.length),a=o,l=e.inputs[0],d=th(a,e.inputs[0].dims.length);d.length>0&&(l=e.compute(Nr(e.inputs[0],d),{inputs:[0],outputs:[-1]})[0],a=Jp(a.length,l.dims.length));let[p,u]=Yp(l.dims,a),h=p;i.keepDims&&(h=Zp(p,o)),e.compute(rh(r,i.cacheKey,[l],s,e.inputs[0].dataType,h,u),{inputs:[l]})},sh=(e,r)=>{ns(e,"ReduceMeanShared",r,"mean")},nh=(e,r)=>{ns(e,"ReduceL1Shared",r,"l1")},ih=(e,r)=>{ns(e,"ReduceL2Shared",r,"l2")},oh=(e,r)=>{ns(e,"ReduceLogSumExpShared",r,"logSumExp")},ah=(e,r)=>{ns(e,"ReduceMaxShared",r,"max")},lh=(e,r)=>{ns(e,"ReduceMinShared",r,"min")},dh=(e,r)=>{ns(e,"ReduceProdShared",r,"prod")},ch=(e,r)=>{ns(e,"ReduceSumShared",r,"sum")},uh=(e,r)=>{ns(e,"ReduceSumSquareShared",r,"sumSquare")},ph=(e,r)=>{ns(e,"ReduceLogSumShared",r,"logSum")}}),is,hh,Ta,Gd,os,mh,_h,fh,gh,wh,yh,Mh,bh,vh,xh,as,Th,Eh,Ph,Ch,Sh,$h,kh,Ih,Ah,Fh,Kd=Ue(()=>{pt(),Mt(),Yt(),xt(),nv(),is=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},hh=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Ta=(e,r,t,s,i,n,o=!1,a=!1)=>{let l=[],d=t[0].dims,p=d.length,u=xe.normalizeAxes(i,p),h=!a&&u.length===0;d.forEach((P,A)=>{h||u.indexOf(A)>=0?o&&l.push(1):l.push(P)});let w=l.length,f=xe.size(l);return{name:e,shaderCache:r,getShaderSource:P=>{let A=[],b=$e("_A",t[0].dataType,p),y=tt("output",n,w),$=s(b,y,u),T=$[2];for(let g=0,M=0;g=0?(o&&M++,T=`for(var j${g}: u32 = 0; j${g} < ${d[g]}; j${g}++) { + ${$[2].includes("last_index")?`let last_index = j${g};`:""} + ${b.indicesSet("input_indices",g,`j${g}`)} + ${T} + }`):(A.push(`${b.indicesSet("input_indices",g,y.indicesGet("output_indices",M))};`),M++);return` - ${P.registerUniform("output_size","u32").declareVariables(v,y)} + ${P.registerUniform("output_size","u32").declareVariables(b,y)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${v.type.indices}; + var input_indices: ${b.type.indices}; let output_indices = ${y.offsetToIndices("global_idx")}; ${A.join(` `)} - ${S[0]} // init ops for reduce max/min - ${S[1]} - ${x} - ${S[3]} - ${S.length===4?y.setByOffset("global_idx","value"):S.slice(4).join(` + ${$[0]} // init ops for reduce max/min + ${$[1]} + ${T} + ${$[3]} + ${$.length===4?y.setByOffset("global_idx","value"):$.slice(4).join(` `)} - }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...nt(d,l)]})}},Wd=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Dt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},os=(e,r,t,s)=>{let i=e.inputs,n=i.length===1?t:Wd(i,t);e.compute(Ta(r,{hint:n.cacheKey,inputDependencies:["rank"]},[i[0]],n.noopWithEmptyAxes&&n.axes.length===0?ph:s,n.axes,i[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},hh=(e,r)=>{is(e.inputs),os(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},mh=(e,r)=>{is(e.inputs),os(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},fh=(e,r)=>{is(e.inputs),os(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},_h=(e,r)=>{is(e.inputs),os(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},gh=(e,r)=>{is(e.inputs),os(e,"ReduceMax",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(t.indicesSet("input_indices",o,0));return[`${n.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},wh=(e,r)=>{is(e.inputs),os(e,"ReduceMean",r,(t,s,i)=>{let n=1;for(let o=0;o=0||i.length===0)&&(n*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},yh=(e,r)=>{is(e.inputs),os(e,"ReduceMin",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(`input_indices[${o}] = 0;`);return[`${n.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Mh=(e,r)=>{is(e.inputs),os(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},bh=(e,r)=>{is(e.inputs),os(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},vh=(e,r)=>{is(e.inputs),os(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},as=(e,r,t)=>{if(r.length===0)return t;let s=1,i=1;for(let n=0;n1024},xh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wh(e,r):rh(e,r)},Th=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?mh(e,r):sh(e,r)},Eh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?fh(e,r):nh(e,r)},Ph=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_h(e,r):ih(e,r)},Ch=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gh(e,r):oh(e,r)},Sh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yh(e,r):ah(e,r)},$h=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mh(e,r):lh(e,r)},kh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bh(e,r):dh(e,r)},Ih=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vh(e,r):ch(e,r)},Ah=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?hh(e,r):uh(e,r)}}),Kd,Fh,Oh,Hd,qb=je(()=>{pt(),Yt(),Gd(),Kd=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Fh=(e,r)=>{Kd(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...nt(d,l)]})}},Gd=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Dt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},os=(e,r,t,s)=>{let i=e.inputs,n=i.length===1?t:Gd(i,t);e.compute(Ta(r,{hint:n.cacheKey,inputDependencies:["rank"]},[i[0]],n.noopWithEmptyAxes&&n.axes.length===0?hh:s,n.axes,i[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},mh=(e,r)=>{is(e.inputs),os(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},_h=(e,r)=>{is(e.inputs),os(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},fh=(e,r)=>{is(e.inputs),os(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},gh=(e,r)=>{is(e.inputs),os(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},wh=(e,r)=>{is(e.inputs),os(e,"ReduceMax",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(t.indicesSet("input_indices",o,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},yh=(e,r)=>{is(e.inputs),os(e,"ReduceMean",r,(t,s,i)=>{let n=1;for(let o=0;o=0||i.length===0)&&(n*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},Mh=(e,r)=>{is(e.inputs),os(e,"ReduceMin",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(`input_indices[${o}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},bh=(e,r)=>{is(e.inputs),os(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},vh=(e,r)=>{is(e.inputs),os(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},xh=(e,r)=>{is(e.inputs),os(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},as=(e,r,t)=>{if(r.length===0)return t;let s=1,i=1;for(let n=0;n1024},Th=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yh(e,r):sh(e,r)},Eh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_h(e,r):nh(e,r)},Ph=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?fh(e,r):ih(e,r)},Ch=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gh(e,r):oh(e,r)},Sh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wh(e,r):ah(e,r)},$h=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mh(e,r):lh(e,r)},kh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bh(e,r):dh(e,r)},Ih=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vh(e,r):ch(e,r)},Ah=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?xh(e,r):uh(e,r)},Fh=(e,r)=>{as(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?mh(e,r):ph(e,r)}}),Hd,Oh,Dh,qd,iv=Ue(()=>{pt(),Yt(),Kd(),Hd=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Oh=(e,r)=>{Hd(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Ta("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Oh=(e,r)=>{Kd(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Ta("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Dh=(e,r)=>{Hd(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Ta("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Hd=e=>Dt(e)}),Dh,Ea,Lh,zh,Bh,Fi,Rh,Nh,qd=je(()=>{pt(),yt(),zd(),vt(),Dh=(e,r)=>{let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4],a=e[5];if(o&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],d=t.dims[1],p=t.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=i.dims[0]/3,h=u,w=h;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let S of r.qkvHiddenSizes)if(S%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=r.qkvHiddenSizes[0],h=r.qkvHiddenSizes[1],w=r.qkvHiddenSizes[2]}let _=d;if(u!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==u+h+w)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let P=0;if(o){if(h!==w)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==h/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(P=o.dims[3])}let A=_+P,v=-1,y=0;if(n)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:d,pastSequenceLength:P,kvSequenceLength:_,totalSequenceLength:A,maxSequenceLength:v,inputHiddenSize:p,hiddenSize:u,vHiddenSize:w,headSize:Math.floor(u/r.numHeads),vHeadSize:Math.floor(w/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ea=(e,r,t)=>r&&e?` + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Ta("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},qd=e=>Dt(e)}),Lh,Ea,zh,Bh,Rh,Fi,Nh,jh,Qd=Ue(()=>{pt(),Mt(),Bd(),xt(),Lh=(e,r)=>{let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4],a=e[5];if(o&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],d=t.dims[1],p=t.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=i.dims[0]/3,h=u,w=h;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let $ of r.qkvHiddenSizes)if($%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=r.qkvHiddenSizes[0],h=r.qkvHiddenSizes[1],w=r.qkvHiddenSizes[2]}let f=d;if(u!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==u+h+w)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let P=0;if(o){if(h!==w)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==h/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(P=o.dims[3])}let A=f+P,b=-1,y=0;if(n)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:d,pastSequenceLength:P,kvSequenceLength:f,totalSequenceLength:A,maxSequenceLength:b,inputHiddenSize:p,hiddenSize:u,vHiddenSize:w,headSize:Math.floor(u/r.numHeads),vHeadSize:Math.floor(w/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ea=(e,r,t)=>r&&e?` let total_sequence_length_input = u32(${r.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; @@ -179,22 +179,22 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas `:` ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; - `,Lh=(e,r,t,s,i,n,o,a)=>{let l=Xt(o?1:n),d=64,p=n/l;p{let y=tt("x",e.dataType,e.dims,l),S=[y],x=o?$e("seq_lens",o.dataType,o.dims):void 0;x&&S.push(x);let g=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;g&&S.push(g);let M=Tr(e.dataType),E=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + `,zh=(e,r,t,s,i,n,o,a)=>{let l=Xt(o?1:n),d=64,p=n/l;p{let y=tt("x",e.dataType,e.dims,l),$=[y],T=o?$e("seq_lens",o.dataType,o.dims):void 0;T&&$.push(T);let g=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;g&&$.push(g);let M=Tr(e.dataType),E=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; - ${v.registerUniforms(E).declareVariables(...S)} - ${v.mainStart([d,1,1])} + ${b.registerUniforms(E).declareVariables(...$)} + ${b.mainStart([d,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; - ${Ea(x,g,!1)} + ${Ea(T,g,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${d}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${o?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; - var thread_max_vector = ${_}(-3.402823e+38f); + var thread_max_vector = ${f}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); + thread_max_vector = max(${f}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()}; workgroupBarrier(); @@ -204,9 +204,9 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas max_value = max(thread_max[i], max_value); } - var sum_vector = ${_}(0); + var sum_vector = ${f}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - sum_vector += exp(${_}(x[offset + i]) - max_value); + sum_vector += exp(${f}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()}; workgroupBarrier(); @@ -222,7 +222,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - var f32input = ${_}(x[offset + i]); + var f32input = ${f}(x[offset + i]); x[offset + i] = ${y.type.value}(exp(f32input - max_value) / sum); } } @@ -230,17 +230,17 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${y.type.value}(${M}(0)); }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${d};${w};${l}`,inputDependencies:P},getShaderSource:A,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:r*t},programUniforms:h})}},zh=(e,r,t,s,i,n,o,a,l)=>{let d=o+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,d],u=e>1&&s,h=n.kvNumHeads?n.kvNumHeads:n.numHeads,w=u?[n.batchSize,h,d,n.headSize]:void 0,_=n.nReps?n.nReps:1,P=n.scale===0?1/Math.sqrt(n.headSize):n.scale,A=Xt(n.headSize),v=n.headSize/A,y=12,S={x:Math.ceil(d/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},x=[{type:12,data:n.sequenceLength},{type:12,data:v},{type:12,data:d},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:P},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:_}],g=u&&s&&xe.size(s.dims)>0,M=["type","type"];g&&M.push("type"),i&&M.push("type"),a&&M.push("type"),l&&M.push("type");let E=[{dims:p,dataType:r.dataType,gpuDataType:0}];u&&E.push({dims:w,dataType:r.dataType,gpuDataType:0});let k=B=>{let R=$e("q",r.dataType,r.dims,A),J=$e("key",t.dataType,t.dims,A),q=[R,J];if(g){let ae=$e("past_key",s.dataType,s.dims,A);q.push(ae)}i&&q.push($e("attention_bias",i.dataType,i.dims));let V=a?$e("seq_lens",a.dataType,a.dims):void 0;V&&q.push(V);let Y=l?$e("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&q.push(Y);let H=tt("output",r.dataType,p),Q=[H];u&&Q.push(tt("present_key",r.dataType,w,A));let ie=Tr(1,A),le=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${d};${w};${l}`,inputDependencies:P},getShaderSource:A,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:r*t},programUniforms:h})}},Bh=(e,r,t,s,i,n,o,a,l)=>{let d=o+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,d],u=e>1&&s,h=n.kvNumHeads?n.kvNumHeads:n.numHeads,w=u?[n.batchSize,h,d,n.headSize]:void 0,f=n.nReps?n.nReps:1,P=n.scale===0?1/Math.sqrt(n.headSize):n.scale,A=Xt(n.headSize),b=n.headSize/A,y=12,$={x:Math.ceil(d/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},T=[{type:12,data:n.sequenceLength},{type:12,data:b},{type:12,data:d},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:P},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:f}],g=u&&s&&xe.size(s.dims)>0,M=["type","type"];g&&M.push("type"),i&&M.push("type"),a&&M.push("type"),l&&M.push("type");let E=[{dims:p,dataType:r.dataType,gpuDataType:0}];u&&E.push({dims:w,dataType:r.dataType,gpuDataType:0});let k=B=>{let N=$e("q",r.dataType,r.dims,A),J=$e("key",t.dataType,t.dims,A),q=[N,J];if(g){let ae=$e("past_key",s.dataType,s.dims,A);q.push(ae)}i&&q.push($e("attention_bias",i.dataType,i.dims));let V=a?$e("seq_lens",a.dataType,a.dims):void 0;V&&q.push(V);let Y=l?$e("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&q.push(Y);let H=tt("output",r.dataType,p),Q=[H];u&&Q.push(tt("present_key",r.dataType,w,A));let ie=Tr(1,A),le=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${y}u; - var tileQ: array<${R.type.storage}, ${y*y}>; - var tileK: array<${R.type.storage}, ${y*y}>; + var tileQ: array<${N.type.storage}, ${y*y}>; + var tileK: array<${N.type.storage}, ${y*y}>; ${B.registerUniforms(le).declareVariables(...q,...Q)} ${B.mainStart([y,y,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; - let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${f===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; @@ -287,7 +287,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas var sum: f32 = ${(()=>{switch(A){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${A}`)}})()}; output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${A};${i!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:E,dispatchGroup:S,programUniforms:x}),getShaderSource:k}},Bh=(e,r,t,s,i,n,o=void 0,a=void 0)=>{let l=n+i.kvSequenceLength,d=i.nReps?i.nReps:1,p=i.vHiddenSize*d,u=e>1&&s,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,w=u?[i.batchSize,h,l,i.headSize]:void 0,_=[i.batchSize,i.sequenceLength,p],P=12,A={x:Math.ceil(i.vHeadSize/P),y:Math.ceil(i.sequenceLength/P),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:l},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:i.kvSequenceLength},{type:12,data:d}],y=u&&s&&xe.size(s.dims)>0,S=["type","type"];y&&S.push("type"),o&&S.push("type"),a&&S.push("type");let x=[{dims:_,dataType:r.dataType,gpuDataType:0}];u&&x.push({dims:w,dataType:r.dataType,gpuDataType:0});let g=M=>{let E=$e("probs",r.dataType,r.dims),k=$e("v",t.dataType,t.dims),B=[E,k];y&&B.push($e("past_value",s.dataType,s.dims));let R=o?$e("seq_lens",o.dataType,o.dims):void 0;o&&B.push(R);let J=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;a&&B.push(J);let q=[tt("output",r.dataType,_)];u&&q.push(tt("present_value",r.dataType,w));let V=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + }`};return{name:"AttentionProbs",shaderCache:{hint:`${A};${i!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:E,dispatchGroup:$,programUniforms:T}),getShaderSource:k}},Rh=(e,r,t,s,i,n,o=void 0,a=void 0)=>{let l=n+i.kvSequenceLength,d=i.nReps?i.nReps:1,p=i.vHiddenSize*d,u=e>1&&s,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,w=u?[i.batchSize,h,l,i.headSize]:void 0,f=[i.batchSize,i.sequenceLength,p],P=12,A={x:Math.ceil(i.vHeadSize/P),y:Math.ceil(i.sequenceLength/P),z:i.batchSize*i.numHeads},b=[{type:12,data:i.sequenceLength},{type:12,data:l},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:i.kvSequenceLength},{type:12,data:d}],y=u&&s&&xe.size(s.dims)>0,$=["type","type"];y&&$.push("type"),o&&$.push("type"),a&&$.push("type");let T=[{dims:f,dataType:r.dataType,gpuDataType:0}];u&&T.push({dims:w,dataType:r.dataType,gpuDataType:0});let g=M=>{let E=$e("probs",r.dataType,r.dims),k=$e("v",t.dataType,t.dims),B=[E,k];y&&B.push($e("past_value",s.dataType,s.dims));let N=o?$e("seq_lens",o.dataType,o.dims):void 0;o&&B.push(N);let J=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;a&&B.push(J);let q=[tt("output",r.dataType,f)];u&&q.push(tt("present_value",r.dataType,w));let V=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${P}u; var tileQ: array<${E.type.value}, ${P*P}>; var tileV: array<${E.type.value}, ${P*P}>; @@ -301,7 +301,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; - ${Ea(R,J,!0)} + ${Ea(N,J,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${y&&u?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; @@ -342,13 +342,13 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas + headIdx * uniforms.N + n; output[outputIdx] = value; } - }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:x,dispatchGroup:A,programUniforms:v}),getShaderSource:g}},Fi=(e,r,t,s,i,n,o,a,l,d,p=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(o?1:0)+(a?1:0)),w=h>1?d.pastSequenceLength:0,_=w+d.kvSequenceLength,P=l&&xe.size(l.dims)>0?l:void 0,A=[r,t];h>1&&o&&xe.size(o.dims)>0&&A.push(o),P&&A.push(P),p&&A.push(p),u&&A.push(u);let v=e.compute(zh(h,r,t,o,P,d,w,p,u),{inputs:A,outputs:h>1?[-1,1]:[-1]})[0];e.compute(Lh(v,d.batchSize,d.numHeads,w,d.sequenceLength,_,p,u),{inputs:p&&u?[v,p,u]:[v],outputs:[]});let y=[v,s];h>1&&a&&xe.size(a.dims)>0&&y.push(a),p&&y.push(p),u&&y.push(u),e.compute(Bh(h,v,s,a,d,w,p,u),{inputs:y,outputs:h>1?[0,2]:[0]})},Rh=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,i=r.inputHiddenSize,n=r.headSize,o=12,a={x:Math.ceil(r.headSize/o),y:Math.ceil(r.sequenceLength/o),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],d=[{type:12,data:s},{type:12,data:i},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=u=>{let h=tt("output_q",l[0].dataType,t),w=tt("output_k",l[0].dataType,t),_=tt("output_v",l[0].dataType,t),P=$e("input",l[0].dataType,l[0].dims),A=$e("weight",l[1].dataType,l[1].dims),v=$e("bias",l[2].dataType,l[2].dims),y=P.type.storage,S=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:$},getRunData:()=>({outputs:T,dispatchGroup:A,programUniforms:b}),getShaderSource:g}},Fi=(e,r,t,s,i,n,o,a,l,d,p=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(o?1:0)+(a?1:0)),w=h>1?d.pastSequenceLength:0,f=w+d.kvSequenceLength,P=l&&xe.size(l.dims)>0?l:void 0,A=[r,t];h>1&&o&&xe.size(o.dims)>0&&A.push(o),P&&A.push(P),p&&A.push(p),u&&A.push(u);let b=e.compute(Bh(h,r,t,o,P,d,w,p,u),{inputs:A,outputs:h>1?[-1,1]:[-1]})[0];e.compute(zh(b,d.batchSize,d.numHeads,w,d.sequenceLength,f,p,u),{inputs:p&&u?[b,p,u]:[b],outputs:[]});let y=[b,s];h>1&&a&&xe.size(a.dims)>0&&y.push(a),p&&y.push(p),u&&y.push(u),e.compute(Rh(h,b,s,a,d,w,p,u),{inputs:y,outputs:h>1?[0,2]:[0]})},Nh=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,i=r.inputHiddenSize,n=r.headSize,o=12,a={x:Math.ceil(r.headSize/o),y:Math.ceil(r.sequenceLength/o),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],d=[{type:12,data:s},{type:12,data:i},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=u=>{let h=tt("output_q",l[0].dataType,t),w=tt("output_k",l[0].dataType,t),f=tt("output_v",l[0].dataType,t),P=$e("input",l[0].dataType,l[0].dims),A=$e("weight",l[1].dataType,l[1].dims),b=$e("bias",l[2].dataType,l[2].dims),y=P.type.storage,$=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${o}u; var tileInput: array<${y}, ${o*o}>; var tileWeightQ: array<${y}, ${o*o}>; var tileWeightK: array<${y}, ${o*o}>; var tileWeightV: array<${y}, ${o*o}>; - ${u.registerUniforms(S).declareVariables(P,A,v,h,w,_)} + ${u.registerUniforms($).declareVariables(P,A,b,h,w,f)} ${u.mainStart([o,o,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; @@ -397,24 +397,24 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas output_k[outputIdx] = valueK; output_v[outputIdx] = valueV; } - }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:d}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Nh=(e,r)=>{let t=Dh(e.inputs,r),[s,i,n]=Rh(e,t);return Fi(e,s,i,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),jh,Uh,Vh,Wh,Qb=je(()=>{ss(),pt(),yt(),Yt(),vt(),jh=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,i,n)=>{let o=i.length;if(o!==s.length)throw new Error(`${n}: num dimensions != ${o}`);i.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},Uh=(e,r)=>{let{epsilon:t,spatial:s,format:i}=r,n=e[0].dims,o=s?Xt(n[n.length-1]):1,a=i==="NHWC"&&n.length>1?o:1,l=xe.size(n)/o,d=s,p=d?n.length:n,u=$e("x",e[0].dataType,e[0].dims,o),h=$e("scale",e[1].dataType,e[1].dims,a),w=$e("bias",e[2].dataType,e[2].dims,a),_=$e("inputMean",e[3].dataType,e[3].dims,a),P=$e("inputVar",e[4].dataType,e[4].dims,a),A=tt("y",e[0].dataType,p,o),v=()=>{let S="";if(s)S=`let cOffset = ${n.length===1?"0u":i==="NHWC"?`outputIndices[${n.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")S=` + }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:d}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},jh=(e,r)=>{let t=Lh(e.inputs,r),[s,i,n]=Nh(e,t);return Fi(e,s,i,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),Uh,Vh,Wh,Gh,ov=Ue(()=>{ss(),pt(),Mt(),Yt(),xt(),Uh=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,i,n)=>{let o=i.length;if(o!==s.length)throw new Error(`${n}: num dimensions != ${o}`);i.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},Vh=(e,r)=>{let{epsilon:t,spatial:s,format:i}=r,n=e[0].dims,o=s?Xt(n[n.length-1]):1,a=i==="NHWC"&&n.length>1?o:1,l=xe.size(n)/o,d=s,p=d?n.length:n,u=$e("x",e[0].dataType,e[0].dims,o),h=$e("scale",e[1].dataType,e[1].dims,a),w=$e("bias",e[2].dataType,e[2].dims,a),f=$e("inputMean",e[3].dataType,e[3].dims,a),P=$e("inputVar",e[4].dataType,e[4].dims,a),A=tt("y",e[0].dataType,p,o),b=()=>{let $="";if(s)$=`let cOffset = ${n.length===1?"0u":i==="NHWC"?`outputIndices[${n.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")$=` ${A.indicesSet("outputIndices","0","0")} - let cOffset = ${A.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${h.type.indices}(0); - cIndices[0] = outputIndices[${n.length-1}];`;for(let x=1;x` + let cOffset = ${A.indicesToOffset("outputIndices")};`;else{$=`var cIndices = ${h.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let T=1;T` const epsilon = ${t}; - ${S.registerUniform("outputSize","u32").declareVariables(u,h,w,_,P,A)} - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${$.registerUniform("outputSize","u32").declareVariables(u,h,w,f,P,A)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${A.offsetToIndices(`global_idx * ${o}`)}; - ${v()} + ${b()} let scale = ${h.getByOffset("cOffset")}; let bias = ${w.getByOffset("cOffset")}; - let inputMean = ${_.getByOffset("cOffset")}; + let inputMean = ${f.getByOffset("cOffset")}; let inputVar = ${P.getByOffset("cOffset")}; let x = ${u.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${A.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${o}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:12,data:l},...nt(n)]:[{type:12,data:l}]})}},Vh=e=>Dt(e),Wh=(e,r)=>{let{inputs:t,outputCount:s}=e,i=Vh({...r,outputCount:s});if(Vt.webgpu.validateInputContent&&jh(t,i),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Uh(t,i))}}),Gh,Kh,Hh,Xb=je(()=>{yt(),vt(),Gh=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Kh=e=>{let r=e[0].dims,t=e[0].dims[2],s=xe.size(r)/4,i=e[0].dataType,n=$e("input",i,r,4),o=$e("bias",i,[t],4),a=$e("residual",i,r,4),l=tt("output",i,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:d=>` + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${o}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:12,data:l},...nt(n)]:[{type:12,data:l}]})}},Wh=e=>Dt(e),Gh=(e,r)=>{let{inputs:t,outputCount:s}=e,i=Wh({...r,outputCount:s});if(Vt.webgpu.validateInputContent&&Uh(t,i),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Vh(t,i))}}),Kh,Hh,qh,av=Ue(()=>{Mt(),xt(),Kh=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Hh=e=>{let r=e[0].dims,t=e[0].dims[2],s=xe.size(r)/4,i=e[0].dataType,n=$e("input",i,r,4),o=$e("bias",i,[t],4),a=$e("residual",i,r,4),l=tt("output",i,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:d=>` const channels = ${t}u / 4; ${d.declareVariables(n,o,a,l)} @@ -423,7 +423,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas let value = ${n.getByOffset("global_idx")} + ${o.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} - }`}},Hh=e=>{Gh(e.inputs),e.compute(Kh(e.inputs))}}),qh,$t,Qh,Xh,Jh,Yh,Zh,em,tm,rm,sm,nm,im,om,am,lm,Oi,dm,Pa,cm,um,pm,hm,mm,fm,_m,gm,wm,ym,Mm,bm,vm,xm,Tm,Em,Qd,Pm,Xd,Jd,Cm,Sm,$m,km,Im,Am,Yd=je(()=>{pt(),yt(),Yt(),vt(),qh=(e,r,t,s,i,n,o)=>{let a=Math.ceil(r/4),l="";typeof i=="string"?l=`${i}(a)`:l=i("a");let d=$e("inputData",t,[a],4),p=tt("outputData",s,[a],4),u=[{name:"vec_size",type:"u32"}];return o&&u.push(...o),` + }`}},qh=e=>{Kh(e.inputs),e.compute(Hh(e.inputs))}}),Qh,$t,Xh,Jh,Yh,Zh,em,tm,rm,sm,nm,im,om,am,lm,dm,Oi,cm,Pa,um,pm,hm,mm,_m,fm,gm,wm,ym,Mm,bm,vm,xm,Tm,Em,Pm,Xd,Cm,Jd,Yd,Sm,$m,km,Im,Am,Fm,Zd=Ue(()=>{pt(),Mt(),Yt(),xt(),Qh=(e,r,t,s,i,n,o)=>{let a=Math.ceil(r/4),l="";typeof i=="string"?l=`${i}(a)`:l=i("a");let d=$e("inputData",t,[a],4),p=tt("outputData",s,[a],4),u=[{name:"vec_size",type:"u32"}];return o&&u.push(...o),` ${e.registerUniforms(u).declareVariables(d,p)} ${n??""} @@ -433,7 +433,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas let a = ${d.getByOffset("global_idx")}; ${p.setByOffset("global_idx",l)} - }`},$t=(e,r,t,s,i,n=e.dataType,o,a)=>{let l=[{type:12,data:Math.ceil(xe.size(e.dims)/4)}];return o&&l.push(...o),{name:r,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:d=>qh(d,xe.size(e.dims),e.dataType,n,t,s,a),getRunData:d=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(xe.size(d[0].dims)/64/4)},programUniforms:l})}},Qh=e=>{e.compute($t(e.inputs[0],"Abs","abs"))},Xh=e=>{e.compute($t(e.inputs[0],"Acos","acos"))},Jh=e=>{e.compute($t(e.inputs[0],"Acosh","acosh"))},Yh=e=>{e.compute($t(e.inputs[0],"Asin","asin"))},Zh=e=>{e.compute($t(e.inputs[0],"Asinh","asinh"))},em=e=>{e.compute($t(e.inputs[0],"Atan","atan"))},tm=e=>{e.compute($t(e.inputs[0],"Atanh","atanh"))},rm=e=>Dt(e),sm=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute($t(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},nm=e=>{let r,t,s=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Dt({min:r,max:t})},im=(e,r)=>{let t=r||nm(e.inputs),s=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},om=e=>{e.compute($t(e.inputs[0],"Ceil","ceil"))},am=e=>{e.compute($t(e.inputs[0],"Cos","cos"))},lm=e=>{e.compute($t(e.inputs[0],"Cosh","cosh"))},Oi=e=>Dt(e),dm=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + }`},$t=(e,r,t,s,i,n=e.dataType,o,a)=>{let l=[{type:12,data:Math.ceil(xe.size(e.dims)/4)}];return o&&l.push(...o),{name:r,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:d=>Qh(d,xe.size(e.dims),e.dataType,n,t,s,a),getRunData:d=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(xe.size(d[0].dims)/64/4)},programUniforms:l})}},Xh=e=>{e.compute($t(e.inputs[0],"Abs","abs"))},Jh=e=>{e.compute($t(e.inputs[0],"Acos","acos"))},Yh=e=>{e.compute($t(e.inputs[0],"Acosh","acosh"))},Zh=e=>{e.compute($t(e.inputs[0],"Asin","asin"))},em=e=>{e.compute($t(e.inputs[0],"Asinh","asinh"))},tm=e=>{e.compute($t(e.inputs[0],"Atan","atan"))},rm=e=>{e.compute($t(e.inputs[0],"Atanh","atanh"))},sm=e=>Dt(e),nm=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute($t(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},im=e=>{let r,t,s=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Dt({min:r,max:t})},om=(e,r)=>{let t=r||im(e.inputs),s=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},am=e=>{e.compute($t(e.inputs[0],"Ceil","ceil"))},lm=e=>{e.compute($t(e.inputs[0],"Cos","cos"))},dm=e=>{e.compute($t(e.inputs[0],"Cosh","cosh"))},Oi=e=>Dt(e),cm=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` const elu_alpha_ = ${t}(${r.alpha}); fn elu_f32(a: ${t}) -> ${t} { @@ -454,15 +454,15 @@ fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); -}`,cm=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,Pa(r)))},um=e=>{e.compute($t(e.inputs[0],"Exp","exp"))},pm=e=>{e.compute($t(e.inputs[0],"Floor","floor"))},hm=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,Pa(r)))},mm=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},fm=e=>{e.compute($t(e.inputs[0],"Not",r=>`!${r}`))},_m=e=>{e.compute($t(e.inputs[0],"Neg",r=>`-${r}`))},gm=e=>{e.compute($t(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},wm=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},ym=e=>{e.compute($t(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Mm=e=>Dt(e),bm=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},vm=e=>{e.compute($t(e.inputs[0],"Sin","sin"))},xm=e=>{e.compute($t(e.inputs[0],"Sinh","sinh"))},Tm=e=>{e.compute($t(e.inputs[0],"Sqrt","sqrt"))},Em=e=>{e.compute($t(e.inputs[0],"Tan","tan"))},Qd=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Pm=e=>{e.compute($t(e.inputs[0],"Tanh",Qd))},Xd=(e="f32")=>` +}`,um=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,Pa(r)))},pm=e=>{e.compute($t(e.inputs[0],"Exp","exp"))},hm=e=>{e.compute($t(e.inputs[0],"Floor","floor"))},mm=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,Pa(r)))},_m=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},fm=e=>{e.compute($t(e.inputs[0],"Not",r=>`!${r}`))},gm=e=>{e.compute($t(e.inputs[0],"Neg",r=>`-${r}`))},wm=e=>{e.compute($t(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},ym=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},Mm=e=>{e.compute($t(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},bm=e=>Dt(e),vm=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},xm=e=>{e.compute($t(e.inputs[0],"Sin","sin"))},Tm=e=>{e.compute($t(e.inputs[0],"Sinh","sinh"))},Em=e=>{e.compute($t(e.inputs[0],"Sqrt","sqrt"))},Pm=e=>{e.compute($t(e.inputs[0],"Tan","tan"))},Xd=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Cm=e=>{e.compute($t(e.inputs[0],"Tanh",Xd))},Jd=(e="f32")=>` const fast_gelu_a: ${e} = 0.5; const fast_gelu_b: ${e} = 0.7978845608028654; const fast_gelu_c: ${e} = 0.035677408136300125; fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { - return ${Qd("v")}; + return ${Xd("v")}; } -`,Jd=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Cm=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"FastGelu",Jd,Xd(r),void 0,e.inputs[0].dataType))},Sm=(e,r)=>{let t=Tr(e.inputs[0].dataType);return e.compute($t(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},$m=e=>{e.compute($t(e.inputs[0],"Log","log"))},km=(e,r)=>` +`,Yd=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Sm=e=>{let r=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"FastGelu",Yd,Jd(r),void 0,e.inputs[0].dataType))},$m=(e,r)=>{let t=Tr(e.inputs[0].dataType);return e.compute($t(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},km=e=>{e.compute($t(e.inputs[0],"Log","log"))},Im=(e,r)=>` const alpha = vec4<${e}>(${r}); const one = ${e}(1.0); const zero = ${e}(0.0); @@ -479,7 +479,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } return x * x1; } -`,Im=e=>`quick_gelu_impl(${e})`,Am=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"QuickGelu",Im,km(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Fm,Om,Dm,Jb=je(()=>{yt(),vt(),Yd(),Fm=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Om=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=$e("input",e[0].dataType,e[0].dims,4),s=$e("bias",e[0].dataType,[e[0].dims[2]],4),i=tt("output",e[0].dataType,r,4),n=xe.size(r)/4,o=lr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` +`,Am=e=>`quick_gelu_impl(${e})`,Fm=(e,r)=>{let t=Tr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"QuickGelu",Am,Im(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Om,Dm,Lm,lv=Ue(()=>{Mt(),xt(),Zd(),Om=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Dm=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=$e("input",e[0].dataType,e[0].dims,4),s=$e("bias",e[0].dataType,[e[0].dims[2]],4),i=tt("output",e[0].dataType,r,4),n=xe.size(r)/4,o=lr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; @@ -497,40 +497,40 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${i.setByOffset("global_idx","valueLeft * geluRight")} - }`}},Dm=e=>{Fm(e.inputs),e.compute(Om(e.inputs))}}),Lm,zm,ls,Bm,Rm,Nm,jm,Um,Vm,Wm,Gm,Km,Hm,Yb=je(()=>{pt(),yt(),vt(),Lm=(e,r,t,s,i,n,o,a,l,d,p,u)=>{let h,w;typeof a=="string"?h=w=(y,S)=>`${a}((${y}),(${S}))`:typeof a=="function"?h=w=a:(h=a.scalar,w=a.vector);let _=tt("outputData",p,s.length,4),P=$e("aData",l,r.length,4),A=$e("bData",d,t.length,4),v;if(i)if(n){let y=xe.size(r)===1,S=xe.size(t)===1,x=r.length>0&&r[r.length-1]%4===0,g=t.length>0&&t[t.length-1]%4===0;y||S?v=_.setByOffset("global_idx",w(y?`${P.type.value}(${P.getByOffset("0")}.x)`:P.getByOffset("global_idx"),S?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):v=` - let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; - let offsetA = ${P.broadcastedIndicesToOffset("outputIndices",_)}; - let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",_)}; - ${_.setByOffset("global_idx",w(o||x?P.getByOffset("offsetA / 4u"):`${P.type.value}(${P.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||g?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else v=_.setByOffset("global_idx",w(P.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=(S,x,g="")=>{let M=`aData[indexA${x}][componentA${x}]`,E=`bData[indexB${x}][componentB${x}]`;return` - let outputIndices${x} = ${_.offsetToIndices(`global_idx * 4u + ${x}u`)}; - let offsetA${x} = ${P.broadcastedIndicesToOffset(`outputIndices${x}`,_)}; - let offsetB${x} = ${A.broadcastedIndicesToOffset(`outputIndices${x}`,_)}; - let indexA${x} = offsetA${x} / 4u; - let indexB${x} = offsetB${x} / 4u; - let componentA${x} = offsetA${x} % 4u; - let componentB${x} = offsetB${x} % 4u; - ${S}[${x}] = ${g}(${h(M,E)}); - `};p===9?v=` + }`}},Lm=e=>{Om(e.inputs),e.compute(Dm(e.inputs))}}),zm,Bm,ls,Rm,Nm,jm,Um,Vm,Wm,Gm,Km,Hm,qm,dv=Ue(()=>{pt(),Mt(),xt(),zm=(e,r,t,s,i,n,o,a,l,d,p,u)=>{let h,w;typeof a=="string"?h=w=(y,$)=>`${a}((${y}),(${$}))`:typeof a=="function"?h=w=a:(h=a.scalar,w=a.vector);let f=tt("outputData",p,s.length,4),P=$e("aData",l,r.length,4),A=$e("bData",d,t.length,4),b;if(i)if(n){let y=xe.size(r)===1,$=xe.size(t)===1,T=r.length>0&&r[r.length-1]%4===0,g=t.length>0&&t[t.length-1]%4===0;y||$?b=f.setByOffset("global_idx",w(y?`${P.type.value}(${P.getByOffset("0")}.x)`:P.getByOffset("global_idx"),$?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):b=` + let outputIndices = ${f.offsetToIndices("global_idx * 4u")}; + let offsetA = ${P.broadcastedIndicesToOffset("outputIndices",f)}; + let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",f)}; + ${f.setByOffset("global_idx",w(o||T?P.getByOffset("offsetA / 4u"):`${P.type.value}(${P.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||g?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else b=f.setByOffset("global_idx",w(P.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=($,T,g="")=>{let M=`aData[indexA${T}][componentA${T}]`,E=`bData[indexB${T}][componentB${T}]`;return` + let outputIndices${T} = ${f.offsetToIndices(`global_idx * 4u + ${T}u`)}; + let offsetA${T} = ${P.broadcastedIndicesToOffset(`outputIndices${T}`,f)}; + let offsetB${T} = ${A.broadcastedIndicesToOffset(`outputIndices${T}`,f)}; + let indexA${T} = offsetA${T} / 4u; + let indexB${T} = offsetB${T} / 4u; + let componentA${T} = offsetA${T} % 4u; + let componentB${T} = offsetB${T} % 4u; + ${$}[${T}] = ${g}(${h(M,E)}); + `};p===9?b=` var data = vec4(0); ${y("data",0,"u32")} ${y("data",1,"u32")} ${y("data",2,"u32")} ${y("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:v=` + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:b=` ${y("outputData[global_idx]",0)} ${y("outputData[global_idx]",1)} ${y("outputData[global_idx]",2)} ${y("outputData[global_idx]",3)} `}return` - ${e.registerUniform("vec_size","u32").declareVariables(P,A,_)} + ${e.registerUniform("vec_size","u32").declareVariables(P,A,f)} ${u??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${v} - }`},zm=(e,r,t,s,i,n,o=t.dataType)=>{let a=t.dims.map(P=>Number(P)??1),l=s.dims.map(P=>Number(P)??1),d=!xe.areEqual(a,l),p=a,u=xe.size(a),h=!1,w=!1,_=[d];if(d){let P=Nn.calcShape(a,l,!1);if(!P)throw new Error("Can't perform binary op on the given tensors");p=P.slice(),u=xe.size(p);let A=xe.size(a)===1,v=xe.size(l)===1,y=a.length>0&&a[a.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;_.push(A),_.push(v),_.push(y),_.push(S);let x=1;for(let g=1;gP.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:P=>Lm(P,a,l,p,h,d,w,i,t.dataType,s.dataType,o,n),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(xe.size(p)/4)},...nt(a,l,p)]})}},ls=(e,r,t,s,i,n)=>{e.compute(zm(r,i??"",e.inputs[0],e.inputs[1],t,s,n))},Bm=e=>{ls(e,"Add",(r,t)=>`${r}+${t}`)},Rm=e=>{ls(e,"Div",(r,t)=>`${r}/${t}`)},Nm=e=>{ls(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},jm=e=>{ls(e,"Mul",(r,t)=>`${r}*${t}`)},Um=e=>{let r=$e("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ls(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + ${b} + }`},Bm=(e,r,t,s,i,n,o=t.dataType)=>{let a=t.dims.map(P=>Number(P)??1),l=s.dims.map(P=>Number(P)??1),d=!xe.areEqual(a,l),p=a,u=xe.size(a),h=!1,w=!1,f=[d];if(d){let P=Nn.calcShape(a,l,!1);if(!P)throw new Error("Can't perform binary op on the given tensors");p=P.slice(),u=xe.size(p);let A=xe.size(a)===1,b=xe.size(l)===1,y=a.length>0&&a[a.length-1]%4===0,$=l.length>0&&l[l.length-1]%4===0;f.push(A),f.push(b),f.push(y),f.push($);let T=1;for(let g=1;gP.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:P=>zm(P,a,l,p,h,d,w,i,t.dataType,s.dataType,o,n),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(xe.size(p)/4)},...nt(a,l,p)]})}},ls=(e,r,t,s,i,n)=>{e.compute(Bm(r,i??"",e.inputs[0],e.inputs[1],t,s,n))},Rm=e=>{ls(e,"Add",(r,t)=>`${r}+${t}`)},Nm=e=>{ls(e,"Div",(r,t)=>`${r}/${t}`)},jm=e=>{ls(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Um=e=>{ls(e,"Mul",(r,t)=>`${r}*${t}`)},Vm=e=>{let r=$e("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ls(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` fn pow_custom(a : ${r}, b : ${r}) -> ${r} { if (b == ${r}(0.0)) { return ${r}(1.0); @@ -543,7 +543,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${r}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } - `)},Vm=e=>{ls(e,"Sub",(r,t)=>`${r}-${t}`)},Wm=e=>{ls(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Gm=e=>{ls(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Km=e=>{ls(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Hm=e=>{ls(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),qm,Qm,Xm,Jm,Ym,Zm,Zb=je(()=>{pt(),yt(),Yt(),vt(),qm=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],i=s.dataType,n=s.dims.length;e.forEach((o,a)=>{if(a!==t){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==n)throw new Error("input tensors should have the same shape");o.dims.forEach((l,d)=>{if(d!==r&&l!==s.dims[d])throw new Error("non concat dimensions must match")})}})},Qm=(e,r)=>` + `)},Wm=e=>{ls(e,"Sub",(r,t)=>`${r}-${t}`)},Gm=e=>{ls(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Km=e=>{ls(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Hm=e=>{ls(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},qm=e=>{ls(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Qm,Xm,Jm,Ym,Zm,e_,cv=Ue(()=>{pt(),Mt(),Yt(),xt(),Qm=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],i=s.dataType,n=s.dims.length;e.forEach((o,a)=>{if(a!==t){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==n)throw new Error("input tensors should have the same shape");o.dims.forEach((l,d)=>{if(d!==r&&l!==s.dims[d])throw new Error("non concat dimensions must match")})}})},Xm=(e,r)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${r}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { @@ -552,12 +552,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } } return ${e}u; - }`,Xm=(e,r)=>{let t=e.length,s=[];for(let i=0;i{let i=xe.size(t),n=new Array(e.length),o=new Array(e.length),a=0,l=[],d=[],p=[{type:12,data:i}];for(let P=0;P`uniforms.sizeInConcatAxis${P}`).join(","),_=P=>` + }`,Jm=(e,r)=>{let t=e.length,s=[];for(let i=0;i{let i=xe.size(t),n=new Array(e.length),o=new Array(e.length),a=0,l=[],d=[],p=[{type:12,data:i}];for(let P=0;P`uniforms.sizeInConcatAxis${P}`).join(","),f=P=>` ${(()=>{P.registerUniform("outputSize","u32");for(let A=0;A) -> vec4<${e}> { ${h} -= sizeInConcatAxis[inputIndex - 1u]; } - ${Xm(o,u)} - }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:_}},Ym=(e,r)=>{let t=e.inputs,s=t[0].dims,i=xe.normalizeAxis(r.axis,s.length);qm(t,i);let n=s.slice();n[i]=t.reduce((a,l)=>a+(l.dims.length>i?l.dims[i]:0),0);let o=t.filter(a=>xe.size(a.dims)>0);e.compute(Jm(o,i,n,t[0].dataType),{inputs:o})},Zm=e=>Dt({axis:e.axis})}),_n,gn,wn,Zd,yn=je(()=>{pt(),yt(),_n=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + ${Jm(o,u)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:f}},Zm=(e,r)=>{let t=e.inputs,s=t[0].dims,i=xe.normalizeAxis(r.axis,s.length);Qm(t,i);let n=s.slice();n[i]=t.reduce((a,l)=>a+(l.dims.length>i?l.dims[i]:0),0);let o=t.filter(a=>xe.size(a.dims)>0);e.compute(Ym(o,i,n,t[0].dataType),{inputs:o})},e_=e=>Dt({axis:e.axis})}),fn,gn,wn,ec,yn=Ue(()=>{pt(),Mt(),fn=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); - `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},gn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},wn=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},Zd=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[Op,Dp];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),hr,ef,ec=je(()=>{hr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},ef=e=>` + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},gn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},wn=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},ec=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[Dp,Lp];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),hr,t_,tc=Ue(()=>{hr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},t_=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),tf,ev=je(()=>{tf=e=>` + `}),r_,uv=Ue(()=>{r_=e=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); @@ -584,20 +584,20 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } -`}),Di,tc,rc=je(()=>{pt(),yt(),vt(),yn(),Di=(e,r,t,s,i)=>{let n=s-t;return` +`}),Di,rc,sc=Ue(()=>{pt(),Mt(),xt(),yn(),Di=(e,r,t,s,i)=>{let n=s-t;return` ${Array.from({length:t}).map((o,a)=>` if (${rt(r.shape,a,r.rank)} != 1) { ${r.indicesSet(e,a,rt(i,a+n,s))} } else { ${r.indicesSet(e,a,0)} }`).join("")} -`},tc=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o[o.length-2],d=a[a.length-1],p=o[o.length-1],u=Xt(d),h=Xt(p),w=Xt(l),_=xe.size(t)/u/w,P=e.length>2,A=s?s.slice(0,-2):t.slice(0,-2),v=[xe.size(A),l,d],y=[{type:12,data:_},{type:12,data:l},{type:12,data:d},{type:12,data:p}];gn(r,y),y.push(...nt(A,o,a)),P&&y.push(...nt(e[2].dims)),y.push(...nt(v));let S=x=>{let g=Ud("batch_dims",e[0].dataType,A.length),M=$e("a",e[0].dataType,o.length,h),E=$e("b",e[1].dataType,a.length,u),k=tt("output",e[0].dataType,v.length,u),B=lr(k.type.tensor),R=_n(r,k.type.value,B),J=[M,E],q="";if(P){let H=i?u:1;J.push($e("bias",e[2].dataType,e[2].dims.length,H)),q=`${i?`value += bias[col / ${H}];`:`value += ${k.type.value}(bias[row + i]);`}`}let V=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];wn(r,V);let Y=()=>{let H=`var a_data: ${M.type.value};`;for(let Q=0;Q{let o=e[0].dims,a=e[1].dims,l=o[o.length-2],d=a[a.length-1],p=o[o.length-1],u=Xt(d),h=Xt(p),w=Xt(l),f=xe.size(t)/u/w,P=e.length>2,A=s?s.slice(0,-2):t.slice(0,-2),b=[xe.size(A),l,d],y=[{type:12,data:f},{type:12,data:l},{type:12,data:d},{type:12,data:p}];gn(r,y),y.push(...nt(A,o,a)),P&&y.push(...nt(e[2].dims)),y.push(...nt(b));let $=T=>{let g=Vd("batch_dims",e[0].dataType,A.length),M=$e("a",e[0].dataType,o.length,h),E=$e("b",e[1].dataType,a.length,u),k=tt("output",e[0].dataType,b.length,u),B=lr(k.type.tensor),N=fn(r,k.type.value,B),J=[M,E],q="";if(P){let H=i?u:1;J.push($e("bias",e[2].dataType,e[2].dims.length,H)),q=`${i?`value += bias[col / ${H}];`:`value += ${k.type.value}(bias[row + i]);`}`}let V=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];wn(r,V);let Y=()=>{let H=`var a_data: ${M.type.value};`;for(let Q=0;Q) -> i32 { for (var i = 0u; i < ${w}u; i++) { var value = values[i]; ${q} - ${R} + ${N} let cur_indices = ${k.type.indices}(batch, row + i, col); let offset = ${k.indicesToOffset("cur_indices")}; ${k.setByOffset(`offset / ${u}`,"value")}; } } - `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${u};${h};${w};${i}`,inputDependencies:P?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:y}),getShaderSource:S}}}),rf,sf,sc,nc,nf,ic,of,Ca,oc=je(()=>{pt(),yt(),vt(),yn(),rc(),ec(),rf=(e,r)=>e?` + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${u};${h};${w};${i}`,inputDependencies:P?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:y}),getShaderSource:$}}}),s_,n_,nc,ic,i_,oc,o_,Ca,ac=Ue(()=>{pt(),Mt(),xt(),yn(),sc(),tc(),s_=(e,r)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); @@ -638,7 +638,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${r?", batchIndices":""}); - `,sf=(e,r)=>e?` + `,n_=(e,r)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; @@ -655,7 +655,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,sc=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32)=>{let l=r[1]*e[1],d=r[0]*e[0],p=i?l:n,u=i?n:l,h=p/r[0],w=n/r[1];if(!((i&&h===4&&e[1]===4||!i&&(h===3||h===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. + }`,nc=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32)=>{let l=r[1]*e[1],d=r[0]*e[0],p=i?l:n,u=i?n:l,h=p/r[0],w=n/r[1];if(!((i&&h===4&&e[1]===4||!i&&(h===3||h===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${h} must be 3 or 4. tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${p/h}>, ${u}>; @@ -692,7 +692,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; - ${rf(i,s)} + ${s_(i,s)} } // Load one tile of B into local memory. @@ -711,7 +711,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${h===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - ${sf(i,h)} + ${n_(i,h)} } workgroupBarrier(); @@ -720,7 +720,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } -}`},nc=(e,r)=>e?` +}`},ic=(e,r)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${r?", batchIndices":""}); @@ -728,7 +728,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${r?", batchIndices":""}); - `,nf=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ic=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32,l=!1)=>{let d=e[1]*r[1],p=e[0]*r[0],u=i?d:n,h=i?n:d;if(!(h%r[1]===0&&u%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let w=h/r[1],_=u/r[0],P=n/r[1],A=l?` + `,i_=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",oc=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32,l=!1)=>{let d=e[1]*r[1],p=e[0]*r[0],u=i?d:n,h=i?n:d;if(!(h%r[1]===0&&u%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let w=h/r[1],f=u/r[0],P=n/r[1],A=l?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${d}; @@ -739,7 +739,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${r[1]}) { for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${r[0]}) { - ${nc(i,s)} + ${ic(i,s)} } } // Load one tile of B into local memory. @@ -785,16 +785,16 @@ let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${d}; let tileRowA = i32(localId.y) * ${w}; -let tileColA = i32(localId.x) * ${_}; +let tileColA = i32(localId.x) * ${f}; let tileRowB = i32(localId.y) * ${P}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; - ${nc(i,s)} + ${ic(i,s)} } } @@ -819,7 +819,7 @@ for (var t = 0; t < num_tiles; t = t + 1) { } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${nf(i)} + ${i_(i)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } @@ -854,7 +854,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, var acc : array, rowPerThread>; ${A} } -`},of=(e,r,t,s,i=!1)=>{let[n,o,a,l]=s,d=lr(s[0].type.tensor);return` +`},o_=(e,r,t,s,i=!1)=>{let[n,o,a,l]=s,d=lr(s[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${hr(e,d)} { var value = ${hr(e,d)}(0.0); let col = colIn * ${e}; @@ -893,11 +893,11 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${l.setByIndices("vec3(coords)","value")} } } - `},Ca=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o.slice(0,-2),d=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),u=xe.size(p),h=o[o.length-2],w=o[o.length-1],_=a[a.length-1],P=w%4===0&&_%4===0,A=h<=8?[4,1,1]:[4,4,1],v=[8,8,1],y=[Math.ceil(_/v[0]/A[0]),Math.ceil(h/v[1]/A[1]),Math.ceil(u/v[2]/A[2])],S=P?4:1,x=[...l,h,w/S],g=x.length,M=[...d,w,_/S],E=M.length,k=[u,h,_/S],B=[{type:6,data:h},{type:6,data:_},{type:6,data:w}];gn(r,B),B.push(...nt(p,x,M));let R=["rank","rank"],J=e.length>2;J&&(B.push(...nt(e[2].dims)),R.push("rank")),B.push(...nt(k));let q=V=>{let Y=p.length,H=Ud("batchDims",e[0].dataType,Y,1),Q=lr(e[0].dataType),ie=$e("a",e[0].dataType,g,S),le=$e("b",e[1].dataType,E,S),ae=tt("result",e[0].dataType,k.length,S),ge=[ie,le];if(J){let X=i?S:1;ge.push($e("bias",e[2].dataType,e[2].dims.length,X))}let N=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];wn(r,N);let O=lr(ae.type.tensor),G=_n(r,ae.type.value,O),ne=of(S,J,G,[H,ie,le,ae],i);return` - ${V.registerUniforms(N).registerInternalVariables(H).declareVariables(...ge,ae)} + `},Ca=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o.slice(0,-2),d=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),u=xe.size(p),h=o[o.length-2],w=o[o.length-1],f=a[a.length-1],P=w%4===0&&f%4===0,A=h<=8?[4,1,1]:[4,4,1],b=[8,8,1],y=[Math.ceil(f/b[0]/A[0]),Math.ceil(h/b[1]/A[1]),Math.ceil(u/b[2]/A[2])],$=P?4:1,T=[...l,h,w/$],g=T.length,M=[...d,w,f/$],E=M.length,k=[u,h,f/$],B=[{type:6,data:h},{type:6,data:f},{type:6,data:w}];gn(r,B),B.push(...nt(p,T,M));let N=["rank","rank"],J=e.length>2;J&&(B.push(...nt(e[2].dims)),N.push("rank")),B.push(...nt(k));let q=V=>{let Y=p.length,H=Vd("batchDims",e[0].dataType,Y,1),Q=lr(e[0].dataType),ie=$e("a",e[0].dataType,g,$),le=$e("b",e[1].dataType,E,$),ae=tt("result",e[0].dataType,k.length,$),we=[ie,le];if(J){let X=i?$:1;we.push($e("bias",e[2].dataType,e[2].dims.length,X))}let R=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];wn(r,R);let O=lr(ae.type.tensor),G=fn(r,ae.type.value,O),ne=o_($,J,G,[H,ie,le,ae],i);return` + ${V.registerUniforms(R).registerInternalVariables(H).declareVariables(...we,ae)} ${ne} - ${P?sc(A,v,Q,H):ic(A,v,Q,H)} - `};return{name:"MatMul",shaderCache:{hint:`${A};${r.activation};${P};${i}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:B}),getShaderSource:q}}}),af,lf,tv=je(()=>{pt(),ks(),vt(),yn(),ec(),ev(),oc(),af=(e,r,t,s,i=!1,n,o=4,a=4,l=4,d="f32")=>{let p=B=>{switch(B){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${d}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${B} is not supported.`)}},u=B=>{switch(B){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${B} is not supported.`)}},h=e?` + ${P?nc(A,b,Q,H):oc(A,b,Q,H)} + `};return{name:"MatMul",shaderCache:{hint:`${A};${r.activation};${P};${i}`,inputDependencies:N},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:B}),getShaderSource:q}}}),a_,l_,pv=Ue(()=>{pt(),ks(),xt(),yn(),tc(),uv(),ac(),a_=(e,r,t,s,i=!1,n,o=4,a=4,l=4,d="f32")=>{let p=B=>{switch(B){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${d}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${B} is not supported.`)}},u=B=>{switch(B){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${B} is not supported.`)}},h=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); @@ -913,26 +913,26 @@ fn main(@builtin(local_invocation_id) localId : vec3, row, col / outWidth, col % outWidth); - `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",P=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",v=e?"col":"row",y=` + `,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",P=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",b=e?"col":"row",y=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${A} / outWidth; let outCol = ${A} % outWidth; - let WRow = ${v} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${v} / inChannels % i32(uniforms.w_shape[1]); + let WRow = ${b} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${b} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; - let xCh = ${v} % inChannels; + let xCh = ${b} % inChannels; var resData = ${hr(o,d)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. - if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${P}) { + if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${P}) { ${h} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${p(o)} } - return resData;`,S=e?r&&s?` + return resData;`,$=e?r&&s?` let col = colIn * ${o}; ${y}`:` let col = colIn * ${o}; @@ -946,7 +946,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${y} } - return ${hr(o,d)}(0.0);`,x=e?s&&t?u(a):` + return ${hr(o,d)}(0.0);`,T=e?s&&t?u(a):` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${u(a)} @@ -956,13 +956,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { ${u(a)} } - return ${hr(a,d)}(0.0);`,g=hr(l,d),M=hr(e?o:a,d),E=hr(e?a:o,d),k=_n(n,g,d);return` + return ${hr(a,d)}(0.0);`,g=hr(l,d),M=hr(e?o:a,d),E=hr(e?a:o,d),k=fn(n,g,d);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { - ${e?S:x} + ${e?$:T} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${E} { - ${e?x:S} + ${e?T:$} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${g}) { @@ -972,57 +972,57 @@ fn main(@builtin(local_invocation_id) localId : vec3, var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${w} - ${ef(i)} + ${t_(i)} ${k} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } - }`},lf=(e,r,t,s,i,n,o,a,l)=>{let d=r.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],u=t[0],h=d?t[2]:t[3],w=d?t[1]:t[2],_=d?t[3]:t[1],P=d&&(p%4===0||p%3===0)&&_%4===0,A=d?_:h*w,v=d?h*w:_,y=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],x=[Math.ceil(A/y[0]/S[0]),Math.ceil(v/y[1]/S[1]),Math.ceil(u/y[2]/S[2])];St("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${x}`);let g=P?d&&p%4!==0?3:4:1,M=y[1]*S[1],E=y[0]*S[0],k=Math.max(y[0]*g,y[1]),B=s%M===0,R=i%E===0,J=n%k===0,q=P?[g,4,4]:[1,1,1],V=[{type:6,data:s},{type:6,data:i},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];gn(r,V),V.push(...nt(e[0].dims,e[1].dims));let Y=["rank","rank"];o&&(V.push(...nt(e[2].dims)),Y.push("rank")),V.push(...nt(t));let H=Q=>{let ie=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];wn(r,ie);let le=P?4:1,ae=lr(e[0].dataType),ge=` + }`},l_=(e,r,t,s,i,n,o,a,l)=>{let d=r.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],u=t[0],h=d?t[2]:t[3],w=d?t[1]:t[2],f=d?t[3]:t[1],P=d&&(p%4===0||p%3===0)&&f%4===0,A=d?f:h*w,b=d?h*w:f,y=[8,8,1],$=s<=8?[4,1,1]:[4,4,1],T=[Math.ceil(A/y[0]/$[0]),Math.ceil(b/y[1]/$[1]),Math.ceil(u/y[2]/$[2])];St("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let g=P?d&&p%4!==0?3:4:1,M=y[1]*$[1],E=y[0]*$[0],k=Math.max(y[0]*g,y[1]),B=s%M===0,N=i%E===0,J=n%k===0,q=P?[g,4,4]:[1,1,1],V=[{type:6,data:s},{type:6,data:i},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];gn(r,V),V.push(...nt(e[0].dims,e[1].dims));let Y=["rank","rank"];o&&(V.push(...nt(e[2].dims)),Y.push("rank")),V.push(...nt(t));let H=Q=>{let ie=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];wn(r,ie);let le=P?4:1,ae=lr(e[0].dataType),we=` fn setOutputAtIndex(flatIndex : i32, value : ${P?`vec4<${ae}>`:ae}) { result[flatIndex] = ${P?`vec4<${ae}>`:ae}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${P?`vec4<${ae}>`:ae}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${P?"/ 4":""}, value); - }`,N=$e("x",e[0].dataType,e[0].dims.length,g===3?1:g),O=$e("w",e[1].dataType,e[1].dims.length,le),G=[N,O],ne=tt("result",e[0].dataType,t.length,le);if(o){let X=$e("bias",e[2].dataType,e[2].dims.length,le);G.push(X),ge+=` + }`,R=$e("x",e[0].dataType,e[0].dims.length,g===3?1:g),O=$e("w",e[1].dataType,e[1].dims.length,le),G=[R,O],ne=tt("result",e[0].dataType,t.length,le);if(o){let X=$e("bias",e[2].dataType,e[2].dims.length,le);G.push(X),we+=` fn getBiasByOutputCoords(coords : vec4) -> ${P?`vec4<${ae}>`:ae} { return bias[coords.${d?"w":"y"}${P?"/ 4":""}]; }`}return` - ${tf("uniforms.result_strides")} + ${r_("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${Q.registerUniforms(ie).declareVariables(...G,ne)} - ${ge} - ${af(d,B,R,J,o,r,q[0],q[1],q[2],ae)} - ${P?sc(S,y,ae,void 0,!d,k):ic(S,y,ae,void 0,!d,k,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${g};${P};${B};${R};${J};${M};${E};${k}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:V}),getShaderSource:H}}}),df,ac,Li,cf,lc,uf,pf,hf,rv=je(()=>{pt(),ks(),yt(),vt(),yn(),ec(),df=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Li=(e,r)=>r<=1?e:e+(e-1)*(r-1),cf=(e,r,t,s=1)=>{let i=Li(r,s);return Math.floor((e[0]*(t-1)-t+i)/2)},lc=(e,r,t,s,i)=>{i==null&&(i=cf(e,r[0],s[0]));let n=[0,0,0,t];for(let o=0;o<3;o++)e[o]+2*i>=r[o]&&(n[o]=Math.trunc((e[o]-r[o]+2*i)/s[o]+1));return n},uf=(e,r,t,s,i,n,o,a,l,d)=>{let p,u,h,w;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=lc([r,t,s,1],[a,l,d],1,[i,n,o],e);u=_[0],h=_[1],w=_[2]}else if(Array.isArray(e)){if(!e.every((P,A,v)=>P===v[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=lc([r,t,s,1],[a,l,d],1,[i,n,o],e[0]);u=_[0],h=_[1],w=_[2]}else if(e==="SAME_UPPER"){u=Math.ceil(r/i),h=Math.ceil(t/n),w=Math.ceil(s/o);let _=(u-1)*i+a-r,P=(h-1)*n+l-t,A=(w-1)*o+d-s,v=Math.floor(_/2),y=_-v,S=Math.floor(P/2),x=P-S,g=Math.floor(A/2),M=A-g;p={top:S,bottom:x,left:g,right:M,front:v,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:u,outHeight:h,outWidth:w}},pf=(e,r,t,s,i,n=!1,o="channelsLast")=>{let a,l,d,p,u;if(o==="channelsLast")[a,l,d,p,u]=e;else if(o==="channelsFirst")[a,u,l,d,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,,w,_,P]=r,[A,v,y]=ac(t),[S,x,g]=ac(s),M=Li(w,S),E=Li(_,x),k=Li(P,g),{padInfo:B,outDepth:R,outHeight:J,outWidth:q}=uf(i,l,d,p,A,v,y,M,E,k),V=n?h*u:h,Y=[0,0,0,0,0];return o==="channelsFirst"?Y=[a,V,R,J,q]:o==="channelsLast"&&(Y=[a,R,J,q,V]),{batchSize:a,dataFormat:o,inDepth:l,inHeight:d,inWidth:p,inChannels:u,outDepth:R,outHeight:J,outWidth:q,outChannels:V,padInfo:B,strideDepth:A,strideHeight:v,strideWidth:y,filterDepth:w,filterHeight:_,filterWidth:P,effectiveFilterDepth:M,effectiveFilterHeight:E,effectiveFilterWidth:k,dilationDepth:S,dilationHeight:x,dilationWidth:g,inShape:e,outShape:Y,filterShape:r}},hf=(e,r,t,s,i,n)=>{let o=n==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((A,v)=>v)},d=[Math.ceil(df(l.x.map(A=>t[A]))/a[0]),1,1];St("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${d}`);let p=1,u=xe.size(t),h=[{type:12,data:u},{type:12,data:s},{type:12,data:i},{type:12,data:r.strides},{type:12,data:r.dilations}];gn(r,h),h.push(...nt(e[0].dims,e[1].dims));let w=["rank","rank"],_=e.length===3;_&&(h.push(...nt(e[2].dims)),w.push("rank")),h.push(...nt(t));let P=A=>{let v=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];wn(r,v);let y=1,S=lr(e[0].dataType),x=$e("x",e[0].dataType,e[0].dims.length,p),g=$e("W",e[1].dataType,e[1].dims.length,y),M=[x,g],E=tt("result",e[0].dataType,t.length,y),k="";if(_){let J=$e("bias",e[2].dataType,e[2].dims.length,y);M.push(J),k+=` - fn getBiasByOutputCoords(coords : array) -> ${S} { + ${we} + ${a_(d,B,N,J,o,r,q[0],q[1],q[2],ae)} + ${P?nc($,y,ae,void 0,!d,k):oc($,y,ae,void 0,!d,k,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${g};${P};${B};${N};${J};${M};${E};${k}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:V}),getShaderSource:H}}}),d_,lc,Li,c_,dc,u_,p_,h_,hv=Ue(()=>{pt(),ks(),Mt(),xt(),yn(),tc(),d_=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Li=(e,r)=>r<=1?e:e+(e-1)*(r-1),c_=(e,r,t,s=1)=>{let i=Li(r,s);return Math.floor((e[0]*(t-1)-t+i)/2)},dc=(e,r,t,s,i)=>{i==null&&(i=c_(e,r[0],s[0]));let n=[0,0,0,t];for(let o=0;o<3;o++)e[o]+2*i>=r[o]&&(n[o]=Math.trunc((e[o]-r[o]+2*i)/s[o]+1));return n},u_=(e,r,t,s,i,n,o,a,l,d)=>{let p,u,h,w;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=dc([r,t,s,1],[a,l,d],1,[i,n,o],e);u=f[0],h=f[1],w=f[2]}else if(Array.isArray(e)){if(!e.every((P,A,b)=>P===b[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let f=dc([r,t,s,1],[a,l,d],1,[i,n,o],e[0]);u=f[0],h=f[1],w=f[2]}else if(e==="SAME_UPPER"){u=Math.ceil(r/i),h=Math.ceil(t/n),w=Math.ceil(s/o);let f=(u-1)*i+a-r,P=(h-1)*n+l-t,A=(w-1)*o+d-s,b=Math.floor(f/2),y=f-b,$=Math.floor(P/2),T=P-$,g=Math.floor(A/2),M=A-g;p={top:$,bottom:T,left:g,right:M,front:b,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:u,outHeight:h,outWidth:w}},p_=(e,r,t,s,i,n=!1,o="channelsLast")=>{let a,l,d,p,u;if(o==="channelsLast")[a,l,d,p,u]=e;else if(o==="channelsFirst")[a,u,l,d,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,,w,f,P]=r,[A,b,y]=lc(t),[$,T,g]=lc(s),M=Li(w,$),E=Li(f,T),k=Li(P,g),{padInfo:B,outDepth:N,outHeight:J,outWidth:q}=u_(i,l,d,p,A,b,y,M,E,k),V=n?h*u:h,Y=[0,0,0,0,0];return o==="channelsFirst"?Y=[a,V,N,J,q]:o==="channelsLast"&&(Y=[a,N,J,q,V]),{batchSize:a,dataFormat:o,inDepth:l,inHeight:d,inWidth:p,inChannels:u,outDepth:N,outHeight:J,outWidth:q,outChannels:V,padInfo:B,strideDepth:A,strideHeight:b,strideWidth:y,filterDepth:w,filterHeight:f,filterWidth:P,effectiveFilterDepth:M,effectiveFilterHeight:E,effectiveFilterWidth:k,dilationDepth:$,dilationHeight:T,dilationWidth:g,inShape:e,outShape:Y,filterShape:r}},h_=(e,r,t,s,i,n)=>{let o=n==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((A,b)=>b)},d=[Math.ceil(d_(l.x.map(A=>t[A]))/a[0]),1,1];St("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${d}`);let p=1,u=xe.size(t),h=[{type:12,data:u},{type:12,data:s},{type:12,data:i},{type:12,data:r.strides},{type:12,data:r.dilations}];gn(r,h),h.push(...nt(e[0].dims,e[1].dims));let w=["rank","rank"],f=e.length===3;f&&(h.push(...nt(e[2].dims)),w.push("rank")),h.push(...nt(t));let P=A=>{let b=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];wn(r,b);let y=1,$=lr(e[0].dataType),T=$e("x",e[0].dataType,e[0].dims.length,p),g=$e("W",e[1].dataType,e[1].dims.length,y),M=[T,g],E=tt("result",e[0].dataType,t.length,y),k="";if(f){let J=$e("bias",e[2].dataType,e[2].dims.length,y);M.push(J),k+=` + fn getBiasByOutputCoords(coords : array) -> ${$} { return bias[${o?rt("coords",4,5):rt("coords",1,5)}]; - }`}let B=hr(p,S),R=_n(r,B,S);return` + }`}let B=hr(p,$),N=fn(r,B,$);return` ${k} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); - return ${x.getByIndices("aIndices")}; + return ${T.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${g.getByIndices("aIndices")}; } - ${A.registerUniforms(v).declareVariables(...M,E)} + ${A.registerUniforms(b).declareVariables(...M,E)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${E.offsetToIndices("global_idx")}; - let batch = ${rt("coords",0,x.rank)}; - let d2 = ${o?rt("coords",x.rank-1,x.rank):rt("coords",1,x.rank)}; - let xFRCCorner = vec3(${o?rt("coords",1,x.rank):rt("coords",2,x.rank)}, - ${o?rt("coords",2,x.rank):rt("coords",3,x.rank)}, - ${o?rt("coords",3,x.rank):rt("coords",4,x.rank)}) * uniforms.strides - uniforms.pads; + let batch = ${rt("coords",0,T.rank)}; + let d2 = ${o?rt("coords",T.rank-1,T.rank):rt("coords",1,T.rank)}; + let xFRCCorner = vec3(${o?rt("coords",1,T.rank):rt("coords",2,T.rank)}, + ${o?rt("coords",2,T.rank):rt("coords",3,T.rank)}, + ${o?rt("coords",3,T.rank):rt("coords",4,T.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; - let xShapeY = ${o?rt("uniforms.x_shape",1,x.rank):rt("uniforms.x_shape",2,x.rank)}; - let xShapeZ = ${o?rt("uniforms.x_shape",2,x.rank):rt("uniforms.x_shape",3,x.rank)}; - let xShapeW = ${o?rt("uniforms.x_shape",3,x.rank):rt("uniforms.x_shape",4,x.rank)}; - let xShapeU = ${o?rt("uniforms.x_shape",4,x.rank):rt("uniforms.x_shape",1,x.rank)}; + let xShapeY = ${o?rt("uniforms.x_shape",1,T.rank):rt("uniforms.x_shape",2,T.rank)}; + let xShapeZ = ${o?rt("uniforms.x_shape",2,T.rank):rt("uniforms.x_shape",3,T.rank)}; + let xShapeW = ${o?rt("uniforms.x_shape",3,T.rank):rt("uniforms.x_shape",4,T.rank)}; + let xShapeU = ${o?rt("uniforms.x_shape",4,T.rank):rt("uniforms.x_shape",1,T.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; @@ -1099,10 +1099,10 @@ fn main(@builtin(local_invocation_id) localId : vec3, } } } - ${_?"value = value + getBiasByOutputCoords(coords)":""}; - ${R} + ${f?"value = value + getBiasByOutputCoords(coords)":""}; + ${N} result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${o};${p};${_}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:d[0],y:d[1],z:d[2]},programUniforms:h}),getShaderSource:P}}}),mf,ff,sv=je(()=>{pt(),yt(),vt(),yn(),mf=(e,r,t,s)=>{let i=e.length>2,n=i?"value += b[output_channel];":"",o=e[0].dims,a=e[1].dims,l=r.format==="NHWC",d=l?t[3]:t[1],p=d/r.group,u=l&&p>=4?Xt(d):1,h=xe.size(t)/u,w=[{type:12,data:h},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];gn(r,w),w.push(...nt(o,[a[0],a[1],a[2],a[3]/u]));let _=i?["rank","rank","rank"]:["rank","rank"];w.push(...nt([t[0],t[1],t[2],t[3]/u]));let P=A=>{let v=tt("output",e[0].dataType,t.length,u),y=lr(v.type.tensor),S=_n(r,v.type.value,y),x=$e("x",e[0].dataType,o.length),g=$e("w",e[1].dataType,a.length,u),M=[x,g];i&&M.push($e("b",e[2].dataType,e[2].dims,u));let E=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];wn(r,E);let k=l?` + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${o};${p};${f}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:d[0],y:d[1],z:d[2]},programUniforms:h}),getShaderSource:P}}}),m_,__,mv=Ue(()=>{pt(),Mt(),xt(),yn(),m_=(e,r,t,s)=>{let i=e.length>2,n=i?"value += b[output_channel];":"",o=e[0].dims,a=e[1].dims,l=r.format==="NHWC",d=l?t[3]:t[1],p=d/r.group,u=l&&p>=4?Xt(d):1,h=xe.size(t)/u,w=[{type:12,data:h},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];gn(r,w),w.push(...nt(o,[a[0],a[1],a[2],a[3]/u]));let f=i?["rank","rank","rank"]:["rank","rank"];w.push(...nt([t[0],t[1],t[2],t[3]/u]));let P=A=>{let b=tt("output",e[0].dataType,t.length,u),y=lr(b.type.tensor),$=fn(r,b.type.value,y),T=$e("x",e[0].dataType,o.length),g=$e("w",e[1].dataType,a.length,u),M=[T,g];i&&M.push($e("b",e[2].dataType,e[2].dims,u));let E=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];wn(r,E);let k=l?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; @@ -1118,7 +1118,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; - let xVal = ${x.get("batch","xHeight","xWidth","input_channel")}; + let xVal = ${T.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${g.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } @@ -1140,34 +1140,34 @@ fn main(@builtin(local_invocation_id) localId : vec3, continue; } - let xVal = ${x.get("batch","input_channel","xHeight","xWidth")}; + let xVal = ${T.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${g.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` - ${A.registerUniforms(E).declareVariables(...M,v)} + ${A.registerUniforms(E).declareVariables(...M,b)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${v.offsetToIndices("global_idx")}; + let outputIndices = ${b.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${l?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; - var value: ${v.type.value} = ${v.type.value}(0); + var value: ${b.type.value} = ${b.type.value}(0); ${k} ${n} - ${S} - ${v.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${u}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:P}},ff=(e,r,t,s)=>{let i=e.length>2,n=Xt(t[3]),o=Xt(t[2]),a=xe.size(t)/n/o,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],d=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],u=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];gn(r,u),u.push(...nt(l,d,p));let h=(o-1)*r.strides[1]+d[1],w=_=>{let P=tt("output",e[0].dataType,p.length,n),A=lr(P.type.tensor),v=_n(r,P.type.value,A),y=$e("x",e[0].dataType,l.length,n),S=$e("w",e[1].dataType,d.length,n),x=[y,S];i&&x.push($e("b",e[2].dataType,e[2].dims,n));let g=i?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return wn(r,M),` - ${_.registerUniforms(M).declareVariables(...x,P)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${$} + ${b.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:P}},__=(e,r,t,s)=>{let i=e.length>2,n=Xt(t[3]),o=Xt(t[2]),a=xe.size(t)/n/o,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],d=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],u=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];gn(r,u),u.push(...nt(l,d,p));let h=(o-1)*r.strides[1]+d[1],w=f=>{let P=tt("output",e[0].dataType,p.length,n),A=lr(P.type.tensor),b=fn(r,P.type.value,A),y=$e("x",e[0].dataType,l.length,n),$=$e("w",e[1].dataType,d.length,n),T=[y,$];i&&T.push($e("b",e[2].dataType,e[2].dims,n));let g=i?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return wn(r,M),` + ${f.registerUniforms(M).declareVariables(...T,P)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; @@ -1195,7 +1195,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, } } for (var w_width: u32 = 0u; w_width < ${d[1]}; w_width++) { - let w_val = ${S.get("w_height","w_width","0","output_channel")}; + let w_val = ${$.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${o}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } @@ -1206,10 +1206,10 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var i = 0u; i < ${o}u; i++) { var value = values[i]; ${g} - ${v} + ${b} ${P.set("batch","row","col + i","output_channel","value")}; } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${o};${h};${d[0]};${d[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}),getShaderSource:w}}}),_f,Sa,gf,$a,dc,cc,wf,yf,uc,nv=je(()=>{yt(),tv(),rv(),oc(),sv(),yn(),rc(),Gs(),_f=(e,r,t,s,i,n)=>{let o=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,d=r[0],p=r.slice(2).map((h,w)=>h+(h-1)*(t[w]-1)),u=a.map((h,w)=>h+s[w]+s[w+l]).map((h,w)=>Math.floor((h-p[w]+i[w])/i[w]));return u.splice(0,0,o),u.splice(n?3:1,0,d),u},Sa=[2,3,1,0],gf=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(r.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(r.strides.length!==i)throw new Error(`strides should be ${i}D`);if(r.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},$a=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=Zd(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,n=e.group,o=e.kernel_shape,a=e.pads,l=e.strides,d=e.w_is_const();return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,pads:a,strides:l,wIsConst:d,...r,cacheKey:`${e.format};${r.activation};`}},cc=(e,r,t,s)=>{let i=t.format==="NHWC",n=_f(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,i);if(t.group!==1){let M=[r[0]];if(i){let E=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=E),M.push(E)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(ff(M,t,n,s),{inputs:M}):e.compute(mf(M,t,n,s),{inputs:M});return}let o=r.length===3,a=r[0].dims[i?1:2],l=r[0].dims[i?2:3],d=r[0].dims[i?3:1],p=r[1].dims[2],u=r[1].dims[3],h=n[i?1:2],w=n[i?2:3],_=n[i?3:1],P=i&&p===a&&u===l&&t.pads[0]===0&&t.pads[1]===0;if(P||p===1&&u===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let M=n[0],E,k,B,R=[];if(i){let V=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=V),P){let Y=a*l*d;E=r[0].reshape([1,M,Y]),k=V.reshape([1,Y,_]),B=[1,M,_]}else E=r[0].reshape([M,a*l,d]),k=V.reshape([1,d,_]),B=[M,h*w,_];R.push(E),R.push(k)}else E=r[0].reshape([M,d,a*l]),k=r[1].reshape([1,_,d]),B=[M,_,h*w],R.push(k),R.push(E);o&&R.push(r[2]);let J=B[2],q=R[0].dims[R[0].dims.length-1];J<8&&q<8?e.compute(tc(R,t,n,B,i,s),{inputs:R}):e.compute(Ca(R,t,n,B,i,s),{inputs:R});return}let A=!0,v=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v);let y=[r[0],v];o&&y.push(r[2]);let S=i?h*w:_,x=i?_:h*w,g=p*u*d;e.compute(lf(y,t,n,S,x,g,o,A,s),{inputs:y})},wf=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let i=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),o=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=$a({...r,pads:i,strides:n,dilations:o,kernelShape:a},s);cc(e,s,l,d=>t?[d[0],d[2],d[3]]:[d[0],d[1],d[3]])},yf=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",i=$a(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,o=pf(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(hf(r,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],s))},uc=(e,r)=>{if(gf(e.inputs,r),e.inputs[0].dims.length===3)wf(e,r);else if(e.inputs[0].dims.length===5)yf(e,e.inputs,r);else{let t=$a(r,e.inputs);cc(e,e.inputs,t)}}}),Mf,iv=je(()=>{pt(),ks(),yt(),vt(),Mf=(e,r,t)=>{let s=e.length>2,i=r.outputShape,n=r.format==="NHWC",o=r.group,a=e[1].dims,l=a[2]/o,d=a[3],p=n?Xt(l):1,u=n&&d===1&&l>=4,h=u?Math.floor(l/4)*4:Math.floor(l/p)*p,w=l-h,_=n?Xt(d):1,P=n?d===1?p:_:1,A=xe.size(i)/_,v=[Math.ceil(A/64),1,1];St("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${v}`);let y=["rank","rank"],S=[r.strides[0],r.strides[1]],x=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],g=[r.dilations[0],r.dilations[1]],M=[x[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),x[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],E=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],k=[{type:12,data:A},{type:12,data:S},{type:12,data:x},{type:12,data:g},{type:12,data:M},{type:6,data:E},{type:12,data:h},{type:12,data:l},{type:12,data:d},...nt(e[0].dims,e[1].dims)];s&&(k.push(...nt(e[2].dims)),y.push("rank")),k.push(...nt(i));let B=R=>{let J=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:S.length},{name:"filter_dims",type:"u32",length:x.length},{name:"dilations",type:"u32",length:x.length},{name:"effective_filter_dims",type:"u32",length:M.length},{name:"pads",type:"i32",length:E.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=lr(e[0].dataType),V=n?1:2,Y=n?2:3,H=n?3:1,Q=$e("W",e[1].dataType,e[1].dims.length,P),ie=$e("Dy",e[0].dataType,e[0].dims.length,p),le=[ie,Q];s&&le.push($e("bias",e[2].dataType,[i[H]].length,_));let ae=tt("result",e[0].dataType,i.length,_),ge=()=>{let G="";if(u)p===4?G+=` + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${o};${h};${d[0]};${d[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}),getShaderSource:w}}}),f_,Sa,g_,$a,cc,uc,w_,y_,pc,_v=Ue(()=>{Mt(),pv(),hv(),ac(),mv(),yn(),sc(),Gs(),f_=(e,r,t,s,i,n)=>{let o=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,d=r[0],p=r.slice(2).map((h,w)=>h+(h-1)*(t[w]-1)),u=a.map((h,w)=>h+s[w]+s[w+l]).map((h,w)=>Math.floor((h-p[w]+i[w])/i[w]));return u.splice(0,0,o),u.splice(n?3:1,0,d),u},Sa=[2,3,1,0],g_=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(r.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(r.strides.length!==i)throw new Error(`strides should be ${i}D`);if(r.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},$a=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=ec(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,n=e.group,o=e.kernel_shape,a=e.pads,l=e.strides,d=e.w_is_const();return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,pads:a,strides:l,wIsConst:d,...r,cacheKey:`${e.format};${r.activation};`}},uc=(e,r,t,s)=>{let i=t.format==="NHWC",n=f_(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,i);if(t.group!==1){let M=[r[0]];if(i){let E=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=E),M.push(E)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(__(M,t,n,s),{inputs:M}):e.compute(m_(M,t,n,s),{inputs:M});return}let o=r.length===3,a=r[0].dims[i?1:2],l=r[0].dims[i?2:3],d=r[0].dims[i?3:1],p=r[1].dims[2],u=r[1].dims[3],h=n[i?1:2],w=n[i?2:3],f=n[i?3:1],P=i&&p===a&&u===l&&t.pads[0]===0&&t.pads[1]===0;if(P||p===1&&u===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let M=n[0],E,k,B,N=[];if(i){let V=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=V),P){let Y=a*l*d;E=r[0].reshape([1,M,Y]),k=V.reshape([1,Y,f]),B=[1,M,f]}else E=r[0].reshape([M,a*l,d]),k=V.reshape([1,d,f]),B=[M,h*w,f];N.push(E),N.push(k)}else E=r[0].reshape([M,d,a*l]),k=r[1].reshape([1,f,d]),B=[M,f,h*w],N.push(k),N.push(E);o&&N.push(r[2]);let J=B[2],q=N[0].dims[N[0].dims.length-1];J<8&&q<8?e.compute(rc(N,t,n,B,i,s),{inputs:N}):e.compute(Ca(N,t,n,B,i,s),{inputs:N});return}let A=!0,b=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=b);let y=[r[0],b];o&&y.push(r[2]);let $=i?h*w:f,T=i?f:h*w,g=p*u*d;e.compute(l_(y,t,n,$,T,g,o,A,s),{inputs:y})},w_=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let i=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),o=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=$a({...r,pads:i,strides:n,dilations:o,kernelShape:a},s);uc(e,s,l,d=>t?[d[0],d[2],d[3]]:[d[0],d[1],d[3]])},y_=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",i=$a(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,o=p_(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(h_(r,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],s))},pc=(e,r)=>{if(g_(e.inputs,r),e.inputs[0].dims.length===3)w_(e,r);else if(e.inputs[0].dims.length===5)y_(e,e.inputs,r);else{let t=$a(r,e.inputs);uc(e,e.inputs,t)}}}),M_,fv=Ue(()=>{pt(),ks(),Mt(),xt(),M_=(e,r,t)=>{let s=e.length>2,i=r.outputShape,n=r.format==="NHWC",o=r.group,a=e[1].dims,l=a[2]/o,d=a[3],p=n?Xt(l):1,u=n&&d===1&&l>=4,h=u?Math.floor(l/4)*4:Math.floor(l/p)*p,w=l-h,f=n?Xt(d):1,P=n?d===1?p:f:1,A=xe.size(i)/f,b=[Math.ceil(A/64),1,1];St("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${b}`);let y=["rank","rank"],$=[r.strides[0],r.strides[1]],T=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],g=[r.dilations[0],r.dilations[1]],M=[T[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),T[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],E=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],k=[{type:12,data:A},{type:12,data:$},{type:12,data:T},{type:12,data:g},{type:12,data:M},{type:6,data:E},{type:12,data:h},{type:12,data:l},{type:12,data:d},...nt(e[0].dims,e[1].dims)];s&&(k.push(...nt(e[2].dims)),y.push("rank")),k.push(...nt(i));let B=N=>{let J=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:$.length},{name:"filter_dims",type:"u32",length:T.length},{name:"dilations",type:"u32",length:T.length},{name:"effective_filter_dims",type:"u32",length:M.length},{name:"pads",type:"i32",length:E.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=lr(e[0].dataType),V=n?1:2,Y=n?2:3,H=n?3:1,Q=$e("W",e[1].dataType,e[1].dims.length,P),ie=$e("Dy",e[0].dataType,e[0].dims.length,p),le=[ie,Q];s&&le.push($e("bias",e[2].dataType,[i[H]].length,f));let ae=tt("result",e[0].dataType,i.length,f),we=()=>{let G="";if(u)p===4?G+=` let xValue = ${ie.getByOffset("x_offset")}; let wValue = ${Q.getByOffset("w_offset")}; dotProd = dotProd + dot(xValue, wValue); @@ -1227,12 +1227,12 @@ fn main(@builtin(local_invocation_id) localId : vec3, let wValue = ${Q.getByOffset(`w_offset / ${P}`)}; dotProd = dotProd + xValue * wValue;`;else for(let ne=0;ne{if(w===0)return"";if(!u)throw new Error(`packInputAs4 ${u} is not true.`);let G="";if(p===1){G+="dotProd = dotProd";for(let ne=0;ne{if(w===0)return"";if(!u)throw new Error(`packInputAs4 ${u} is not true.`);let G="";if(p===1){G+="dotProd = dotProd";for(let ne=0;ne, var w_offset = ${Q.indicesToOffset(`${Q.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${P}; `:""} for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${u?4:p}) { - ${ge()} + ${we()} inputChannel = inputChannel + ${u?4:p}; } - ${N()} + ${R()} wC = wC + uniforms.strides.y - 1; } wR = wR + uniforms.strides[0] - 1; } - let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + let value = dotProd${s?` + bias[d1 / ${f}]`:""}; ${ae.setByOffset("global_idx","value")}; `;return` - ${R.registerUniforms(J).declareVariables(...le,ae)} - ${R.mainStart()} - ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${O}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${P}${_}${u}${w}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:v[0],y:v[1],z:v[2]},outputs:[{dims:t?t(i):i,dataType:e[0].dataType}],programUniforms:k}),getShaderSource:B}}}),bf,vf,xf,pc,Tf,Ef,hc,Pf,Cf,ov=je(()=>{iv(),yn(),Gs(),bf=(e,r,t,s,i,n)=>(e-1)*r+t+(s-1)*i+1-n,vf=(e,r,t,s,i)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[i]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[i]=n)},xf=(e,r,t,s,i,n,o,a,l,d)=>{let p=e.length-2,u=d.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){t.length=0;for(let u=2;uu+h,0)===0){let u=r[0].dims.length-2;l=new Array(u).fill(1)}let d=e.strides.slice();if(d.reduce((u,h)=>u+h,0)===0){let u=r[0].dims.length-2;d=new Array(u).fill(1)}xf(a,t,l,e.autoPad,e.group,i,d,s,o,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:i,outputPadding:o,outputShape:n,dilations:l,strides:d}),p},Tf=e=>{let r=Zd(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,n=e.group,o=e.kernelShape,a=e.pads,l=e.strides,d=e.wIsConst(),p=e.outputPadding,u=e.outputShape;return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,outputPadding:p,outputShape:u,pads:a,strides:l,wIsConst:d,...r,cacheKey:`${e.format};${r.activation};`}},Ef=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((o,a)=>o+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((o,a)=>o+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((o,a)=>o+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((o,a)=>o+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},hc=(e,r,t,s)=>{let i=e.kernelCustomData.wT??e.compute(Nr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let n=[r[0],i];r.length===3&&n.push(r[2]),e.compute(Mf(n,t,s),{inputs:n})},Pf=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let i=r.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let o=r.strides;(o.length===0||o[0]===0)&&(o=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],o=[1].concat(o),n=[1].concat(n),i=[1].concat(i);let l=r.outputPadding;l=[0].concat(l);let d=pc({...r,pads:a,strides:o,dilations:n,kernelShape:i,outputPadding:l},s);hc(e,s,d,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Cf=(e,r)=>{if(Ef(e.inputs,r),e.inputs[0].dims.length===3)Pf(e,r);else{let t=pc(r,e.inputs);hc(e,e.inputs,t)}}}),Sf,$f,kf,av=je(()=>{pt(),yt(),Yt(),vt(),Sf=(e,r,t,s)=>{let i=xe.size(r),n=r.length,o=$e("input",e,n),a=tt("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),d=xe.normalizeAxis(l,n),p=u=>{let h=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,w=rt("uniforms.input_shape","uniforms.axis",n),_=s.reverse?h+(s.exclusive?" + 1":""):"0",P=s.reverse?w:h+(s.exclusive?"":" + 1");return` + ${N.registerUniforms(J).declareVariables(...le,ae)} + ${N.mainStart()} + ${N.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${O}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${P}${f}${u}${w}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:b[0],y:b[1],z:b[2]},outputs:[{dims:t?t(i):i,dataType:e[0].dataType}],programUniforms:k}),getShaderSource:B}}}),b_,v_,x_,hc,T_,E_,mc,P_,C_,gv=Ue(()=>{fv(),yn(),Gs(),b_=(e,r,t,s,i,n)=>(e-1)*r+t+(s-1)*i+1-n,v_=(e,r,t,s,i)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[i]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[i]=n)},x_=(e,r,t,s,i,n,o,a,l,d)=>{let p=e.length-2,u=d.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){t.length=0;for(let u=2;uu+h,0)===0){let u=r[0].dims.length-2;l=new Array(u).fill(1)}let d=e.strides.slice();if(d.reduce((u,h)=>u+h,0)===0){let u=r[0].dims.length-2;d=new Array(u).fill(1)}x_(a,t,l,e.autoPad,e.group,i,d,s,o,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:i,outputPadding:o,outputShape:n,dilations:l,strides:d}),p},T_=e=>{let r=ec(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,n=e.group,o=e.kernelShape,a=e.pads,l=e.strides,d=e.wIsConst(),p=e.outputPadding,u=e.outputShape;return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,outputPadding:p,outputShape:u,pads:a,strides:l,wIsConst:d,...r,cacheKey:`${e.format};${r.activation};`}},E_=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((o,a)=>o+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((o,a)=>o+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((o,a)=>o+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((o,a)=>o+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},mc=(e,r,t,s)=>{let i=e.kernelCustomData.wT??e.compute(Nr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let n=[r[0],i];r.length===3&&n.push(r[2]),e.compute(M_(n,t,s),{inputs:n})},P_=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let i=r.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let o=r.strides;(o.length===0||o[0]===0)&&(o=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],o=[1].concat(o),n=[1].concat(n),i=[1].concat(i);let l=r.outputPadding;l=[0].concat(l);let d=hc({...r,pads:a,strides:o,dilations:n,kernelShape:i,outputPadding:l},s);mc(e,s,d,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},C_=(e,r)=>{if(E_(e.inputs,r),e.inputs[0].dims.length===3)P_(e,r);else{let t=hc(r,e.inputs);mc(e,e.inputs,t)}}}),S_,$_,k_,wv=Ue(()=>{pt(),Mt(),Yt(),xt(),S_=(e,r,t,s)=>{let i=xe.size(r),n=r.length,o=$e("input",e,n),a=tt("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),d=xe.normalizeAxis(l,n),p=u=>{let h=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,w=rt("uniforms.input_shape","uniforms.axis",n),f=s.reverse?h+(s.exclusive?" + 1":""):"0",P=s.reverse?w:h+(s.exclusive?"":" + 1");return` ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,a)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${a.offsetToIndices("global_idx")}; var sum = ${a.type.value}(0); - let first : i32 = ${_}; + let first : i32 = ${f}; let last : i32 = ${P}; for (var i : i32 = first; i < last; i++) { ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${o.getByIndices("inputIndices")}; } ${a.setByOffset("global_idx","sum")}; - }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:d},...nt(r,r)]}),getShaderSource:p}},$f=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,i=e.inputs[1];e.compute(Sf(s,t,i,r),{inputs:[0]})},kf=e=>{let r=e.exclusive===1,t=e.reverse===1;return Dt({exclusive:r,reverse:t})}}),If,Af,Ff,Of,Df,lv=je(()=>{pt(),yt(),Yt(),vt(),If=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Af=(e,r,t,s)=>{let i=[];i.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:d},...nt(r,r)]}),getShaderSource:p}},$_=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,i=e.inputs[1];e.compute(S_(s,t,i,r),{inputs:[0]})},k_=e=>{let r=e.exclusive===1,t=e.reverse===1;return Dt({exclusive:r,reverse:t})}}),I_,A_,F_,O_,D_,yv=Ue(()=>{pt(),Mt(),Yt(),xt(),I_=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},A_=(e,r,t,s)=>{let i=[];i.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { var a: ${t.type.indices};`);for(let n=0;n{let t,s,i,n,o,a,l=r.format==="NHWC",d=r.blocksize,p=r.mode==="DCR";l?([t,s,i,n]=e.dims,o=p?[t,s,i,d,d,n/d**2]:[t,s,i,n/d**2,d,d],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,i,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=p?[t,d,d,n/d**2,s,i]:[t,n/d**2,d,d,s,i],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(o),h=u.dims.length,w=e.dataType,_=$e("a",w,h),P=tt("output",w,h),A=v=>` - ${v.registerUniform("output_size","u32").declareVariables(_,P)} +`)},F_=(e,r)=>{let t,s,i,n,o,a,l=r.format==="NHWC",d=r.blocksize,p=r.mode==="DCR";l?([t,s,i,n]=e.dims,o=p?[t,s,i,d,d,n/d**2]:[t,s,i,n/d**2,d,d],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,i,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=p?[t,d,d,n/d**2,s,i]:[t,n/d**2,d,d,s,i],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(o),h=u.dims.length,w=e.dataType,f=$e("a",w,h),P=tt("output",w,h),A=b=>` + ${b.registerUniform("output_size","u32").declareVariables(f,P)} - ${Af(a,h,_,P)} + ${A_(a,h,f,P)} - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${P.offsetToIndices("global_idx")}; let aIndices = perm(indices); - ${P.setByOffset("global_idx",_.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:v=>{let y=l?[t,s*d,i*d,n/d**2]:[t,n/d**2,s*d,i*d],S=xe.size(y),x=u.dims,g=xe.sortBasedOnPerm(x,a);return{outputs:[{dims:y,dataType:v[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...nt(x,g)]}},getShaderSource:A}},Of=(e,r)=>{If(e.inputs),e.compute(Ff(e.inputs[0],r))},Df=e=>Dt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ka,zi,mc,Lf,zf,Bf,Rf,fc,Nf,jf,Uf,dv=je(()=>{pt(),yt(),Yt(),vt(),ka="[a-zA-Z]|\\.\\.\\.",zi="("+ka+")+",mc="^"+zi+"$",Lf="("+zi+",)*"+zi,zf="^"+Lf+"$",Bf=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},Rf=class{constructor(e,r){var i;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(zf)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let a=e[o].dims.slice();if(!n.match(RegExp(mc)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,o);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(zi)))throw new Error("Invalid RHS");(i=s.match(RegExp(ka,"g")))==null||i.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let i=t.length,n=!1,o=[],a=0;if(!e.match(RegExp(mc))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(ka,"g")),d=new Bf(s);return l==null||l.forEach((p,u)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let h=i-l.length+1;if(h<0)throw new Error("Ellipsis out of bounds");if(o=t.slice(a,a+h),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let w=0;we+"_max",Nf=(e,r,t,s)=>{let i=e.map(d=>d.length).map((d,p)=>$e(`input${p}`,r,d)),n=xe.size(s),o=tt("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(d=>!t.rhs.symbolToIndices.has(d)),l=d=>{let p=[],u="var prod = 1.0;",h="var sum = 0.0;",w="sum += prod;",_=[],P=[],A=[],v=[],y=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((x,g)=>{var M;if(t.rhs.symbolToIndices.has(g)){let E=(M=t.rhs.symbolToIndices.get(g))==null?void 0:M[0];E!==void 0&&t.lhs.forEach((k,B)=>{if(x.inputIndices.includes(B)){let R=k.symbolToIndices.get(g);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(J=>{p.push(`${i[B].indicesSet(`input${B}Indices`,J,o.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,k)=>{if(x.inputIndices.includes(k)){let B=E.symbolToIndices.get(g);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(R=>{_.push(`${i[k].indicesSet(`input${k}Indices`,R,`${g}`)}`)}),v.push(`prod *= ${i[k].getByIndices(`input${k}Indices`)};`)}}),P.push(`for(var ${g}: u32 = 0; ${g} < uniforms.${fc(g)}; ${g}++) {`),A.push("}")});let S=y?[...p,`let sum = ${i.map((x,g)=>x.getByIndices(`input${g}Indices`)).join(" * ")};`]:[...p,h,...P,..._,u,...v,w,...A];return` - ${d.registerUniforms(a.map(x=>({name:`${fc(x)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} + ${P.setByOffset("global_idx",f.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:b=>{let y=l?[t,s*d,i*d,n/d**2]:[t,n/d**2,s*d,i*d],$=xe.size(y),T=u.dims,g=xe.sortBasedOnPerm(T,a);return{outputs:[{dims:y,dataType:b[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...nt(T,g)]}},getShaderSource:A}},O_=(e,r)=>{I_(e.inputs),e.compute(F_(e.inputs[0],r))},D_=e=>Dt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ka,zi,_c,L_,z_,B_,R_,fc,N_,j_,U_,Mv=Ue(()=>{pt(),Mt(),Yt(),xt(),ka="[a-zA-Z]|\\.\\.\\.",zi="("+ka+")+",_c="^"+zi+"$",L_="("+zi+",)*"+zi,z_="^"+L_+"$",B_=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},R_=class{constructor(e,r){var i;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(z_)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let a=e[o].dims.slice();if(!n.match(RegExp(_c)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,o);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(zi)))throw new Error("Invalid RHS");(i=s.match(RegExp(ka,"g")))==null||i.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let i=t.length,n=!1,o=[],a=0;if(!e.match(RegExp(_c))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(ka,"g")),d=new B_(s);return l==null||l.forEach((p,u)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let h=i-l.length+1;if(h<0)throw new Error("Ellipsis out of bounds");if(o=t.slice(a,a+h),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let w=0;we+"_max",N_=(e,r,t,s)=>{let i=e.map(d=>d.length).map((d,p)=>$e(`input${p}`,r,d)),n=xe.size(s),o=tt("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(d=>!t.rhs.symbolToIndices.has(d)),l=d=>{let p=[],u="var prod = 1.0;",h="var sum = 0.0;",w="sum += prod;",f=[],P=[],A=[],b=[],y=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((T,g)=>{var M;if(t.rhs.symbolToIndices.has(g)){let E=(M=t.rhs.symbolToIndices.get(g))==null?void 0:M[0];E!==void 0&&t.lhs.forEach((k,B)=>{if(T.inputIndices.includes(B)){let N=k.symbolToIndices.get(g);if(N===void 0)throw new Error("Invalid symbol error");N.forEach(J=>{p.push(`${i[B].indicesSet(`input${B}Indices`,J,o.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,k)=>{if(T.inputIndices.includes(k)){let B=E.symbolToIndices.get(g);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(N=>{f.push(`${i[k].indicesSet(`input${k}Indices`,N,`${g}`)}`)}),b.push(`prod *= ${i[k].getByIndices(`input${k}Indices`)};`)}}),P.push(`for(var ${g}: u32 = 0; ${g} < uniforms.${fc(g)}; ${g}++) {`),A.push("}")});let $=y?[...p,`let sum = ${i.map((T,g)=>T.getByIndices(`input${g}Indices`)).join(" * ")};`]:[...p,h,...P,...f,u,...b,w,...A];return` + ${d.registerUniforms(a.map(T=>({name:`${fc(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${o.offsetToIndices("global_idx")}; - ${i.map((x,g)=>`var input${g}Indices: ${i[g].type.indices};`).join(` + ${i.map((T,g)=>`var input${g}Indices: ${i[g].type.indices};`).join(` `)} - ${S.join(` + ${$.join(` `)}; ${o.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let d=a.filter(u=>t.symbolToInfo.has(u)).map(u=>{var h;return{type:12,data:((h=t.symbolToInfo.get(u))==null?void 0:h.dimValue)||0}});d.push({type:12,data:n});let p=e.map((u,h)=>[...nt(u)]).reduce((u,h)=>u.concat(h),d);return p.push(...nt(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},jf=(e,r)=>{let t=new Rf(e.inputs,r.equation),s=t.outputDims,i=e.inputs.map((n,o)=>n.dims);e.compute(Nf(i,e.inputs[0].dataType,t,s))},Uf=e=>{let r=e.equation.replace(/\s+/g,"");return Dt({equation:r})}}),Vf,_c,Wf,Gf,Kf,cv=je(()=>{pt(),yt(),vt(),Vf=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let i=0;ie.length>r.length?_c(e,r):_c(r,e),Gf=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Wf(r,t),i=e[0].dataType,n=i===9||xe.size(r)===1,o=i===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(xe.size(s)/a),d=u=>{let h=$e("input",i,r.length,o),w=tt("output",i,s.length,a),_;if(i===9){let P=(A,v,y="")=>` - let outputIndices${v} = ${w.offsetToIndices(`outputOffset + ${v}u`)}; - let offset${v} = ${h.broadcastedIndicesToOffset(`outputIndices${v}`,w)}; - let index${v} = offset${v} / 4u; - let component${v} = offset${v} % 4u; - ${A}[${v}] = ${y}(${h.getByOffset(`index${v}`)}[component${v}]); - `;_=` + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let d=a.filter(u=>t.symbolToInfo.has(u)).map(u=>{var h;return{type:12,data:((h=t.symbolToInfo.get(u))==null?void 0:h.dimValue)||0}});d.push({type:12,data:n});let p=e.map((u,h)=>[...nt(u)]).reduce((u,h)=>u.concat(h),d);return p.push(...nt(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},j_=(e,r)=>{let t=new R_(e.inputs,r.equation),s=t.outputDims,i=e.inputs.map((n,o)=>n.dims);e.compute(N_(i,e.inputs[0].dataType,t,s))},U_=e=>{let r=e.equation.replace(/\s+/g,"");return Dt({equation:r})}}),V_,gc,W_,G_,K_,bv=Ue(()=>{pt(),Mt(),xt(),V_=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let i=0;ie.length>r.length?gc(e,r):gc(r,e),G_=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=W_(r,t),i=e[0].dataType,n=i===9||xe.size(r)===1,o=i===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(xe.size(s)/a),d=u=>{let h=$e("input",i,r.length,o),w=tt("output",i,s.length,a),f;if(i===9){let P=(A,b,y="")=>` + let outputIndices${b} = ${w.offsetToIndices(`outputOffset + ${b}u`)}; + let offset${b} = ${h.broadcastedIndicesToOffset(`outputIndices${b}`,w)}; + let index${b} = offset${b} / 4u; + let component${b} = offset${b} % 4u; + ${A}[${b}] = ${y}(${h.getByOffset(`index${b}`)}[component${b}]); + `;f=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${P("data",0,"u32")} @@ -1349,7 +1349,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${P("data",2,"u32")} ${P("data",3,"u32")} ${w.setByOffset("global_idx","data")} - }`}else _=` + }`}else f=` let outputIndices = ${w.offsetToIndices(`global_idx * ${a}`)}; let inputOffset = ${h.broadcastedIndicesToOffset("outputIndices",w)}; let data = ${w.type.value}(${h.getByOffset(`inputOffset / ${o}`)}); @@ -1358,13 +1358,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${u.registerUniform("vec_size","u32").declareVariables(h,w)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${_}`},p=[{type:12,data:l},...nt(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${o}${a}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Kf=e=>{Vf(e.inputs),e.compute(Gf(e.inputs),{inputs:[0]})}}),Hf,qf,uv=je(()=>{pt(),yt(),vt(),Yd(),Hf=e=>{let r=e[0].dataType,t=xe.size(e[0].dims),s=xe.size(e[1].dims),i=s%4===0,n=o=>{let a=$e("x",r,[1],4),l=$e("bias",r,[1],4),d=tt("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=w=>` + ${f}`},p=[{type:12,data:l},...nt(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${o}${a}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},K_=e=>{V_(e.inputs),e.compute(G_(e.inputs),{inputs:[0]})}}),H_,q_,vv=Ue(()=>{pt(),Mt(),xt(),Zd(),H_=e=>{let r=e[0].dataType,t=xe.size(e[0].dims),s=xe.size(e[1].dims),i=s%4===0,n=o=>{let a=$e("x",r,[1],4),l=$e("bias",r,[1],4),d=tt("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=w=>` let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size; let bias${w} = ${l.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`,h=i?` let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${u(0)}${u(1)}${u(2)}${u(3)} let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(p).declareVariables(a,l,d)} - ${Xd(Tr(r))} + ${Jd(Tr(r))} ${o.mainStart(jn)} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} @@ -1372,21 +1372,21 @@ fn main(@builtin(local_invocation_id) localId : vec3, let x = ${a.getByOffset("global_idx")}; ${h} let x_in = x + bias; - ${d.setByOffset("global_idx",Jd("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/jn/4)}})}},qf=e=>{e.inputs.length<2||xe.size(e.inputs[1].dims)===0?Cm(e):e.compute(Hf(e.inputs))}}),Qf,Xf,Jf,Yf,pv=je(()=>{pt(),yt(),Yt(),vt(),Qf=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Xf=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=xe.normalizeAxis(r.axis,i),o=t.slice(0);o.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,d=Math.ceil(xe.size(o)/l),p=[{type:12,data:d},{type:6,data:a},{type:12,data:n},...nt(e[0].dims,e[1].dims,o)],u=h=>{let w=$e("data",e[0].dataType,e[0].dims.length,l),_=$e("inputIndices",e[1].dataType,e[1].dims.length),P=tt("output",e[0].dataType,o.length,l),A=y=>{let S=s.length,x=`var indicesIndices${y} = ${_.type.indices}(0);`;for(let g=0;g1?`indicesIndices${y}[${g}]`:`indicesIndices${y}`} = ${o.length>1?`outputIndices${y}[uniforms.axis + ${g}]`:`outputIndices${y}`};`;x+=` - var idx${y} = ${_.getByIndices(`indicesIndices${y}`)}; + ${d.setByOffset("global_idx",Yd("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/jn/4)}})}},q_=e=>{e.inputs.length<2||xe.size(e.inputs[1].dims)===0?Sm(e):e.compute(H_(e.inputs))}}),Q_,X_,J_,Y_,xv=Ue(()=>{pt(),Mt(),Yt(),xt(),Q_=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},X_=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=xe.normalizeAxis(r.axis,i),o=t.slice(0);o.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,d=Math.ceil(xe.size(o)/l),p=[{type:12,data:d},{type:6,data:a},{type:12,data:n},...nt(e[0].dims,e[1].dims,o)],u=h=>{let w=$e("data",e[0].dataType,e[0].dims.length,l),f=$e("inputIndices",e[1].dataType,e[1].dims.length),P=tt("output",e[0].dataType,o.length,l),A=y=>{let $=s.length,T=`var indicesIndices${y} = ${f.type.indices}(0);`;for(let g=0;g<$;g++)T+=`${$>1?`indicesIndices${y}[${g}]`:`indicesIndices${y}`} = ${o.length>1?`outputIndices${y}[uniforms.axis + ${g}]`:`outputIndices${y}`};`;T+=` + var idx${y} = ${f.getByIndices(`indicesIndices${y}`)}; if (idx${y} < 0) { idx${y} = idx${y} + uniforms.axisDimLimit; } var dataIndices${y} : ${w.type.indices}; - `;for(let g=0,M=0;g1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = u32(idx${y});`,M+=S):(x+=`${i>1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = ${o.length>1?`outputIndices${y}[${M}]`:`outputIndices${y}`};`,M++);return x},v;if(e[0].dataType===9){let y=(S,x,g="")=>` - let outputIndices${x} = ${P.offsetToIndices(`outputOffset + ${x}u`)}; - ${A(x)}; - let offset${x} = ${w.indicesToOffset(`dataIndices${x}`)}; - let index${x} = offset${x} / 4u; - let component${x} = offset${x} % 4u; - ${S}[${x}] = ${g}(${w.getByOffset(`index${x}`)}[component${x}]); - `;v=` + `;for(let g=0,M=0;g1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = u32(idx${y});`,M+=$):(T+=`${i>1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = ${o.length>1?`outputIndices${y}[${M}]`:`outputIndices${y}`};`,M++);return T},b;if(e[0].dataType===9){let y=($,T,g="")=>` + let outputIndices${T} = ${P.offsetToIndices(`outputOffset + ${T}u`)}; + ${A(T)}; + let offset${T} = ${w.indicesToOffset(`dataIndices${T}`)}; + let index${T} = offset${T} / 4u; + let component${T} = offset${T} % 4u; + ${$}[${T}] = ${g}(${w.getByOffset(`index${T}`)}[component${T}]); + `;b=` let outputOffset = global_idx * ${l}; var value = vec4(0); ${y("value",0,"u32")} @@ -1394,17 +1394,17 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${y("value",2,"u32")} ${y("value",3,"u32")} ${P.setByOffset("global_idx","value")} - `}else v=` + `}else b=` let outputIndices = ${P.offsetToIndices("global_idx")}; ${A("")}; let value = ${w.getByIndices("dataIndices")}; ${P.setByOffset("global_idx","value")}; `;return` - ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,_,P)} + ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,f,P)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${v} - }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:u}},Jf=e=>Dt({axis:e.axis}),Yf=(e,r)=>{let t=e.inputs;Qf(t),e.compute(Xf(e.inputs,r))}}),Zf,e_,t_,hv=je(()=>{pt(),yt(),vt(),Zf=(e,r,t,s,i,n,o,a,l)=>{let d=[{type:12,data:n},{type:12,data:s},{type:12,data:i},{type:12,data:t},{type:12,data:o},{type:12,data:a},{type:12,data:l}],p=[n];d.push(...nt(r.dims,p));let u=h=>{let w=$e("indices_data",r.dataType,r.dims.length),_=tt("input_slice_offsets_data",12,1,1),P=[w,_],A=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${b} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:u}},J_=e=>Dt({axis:e.axis}),Y_=(e,r)=>{let t=e.inputs;Q_(t),e.compute(X_(e.inputs,r))}}),Z_,ef,tf,Tv=Ue(()=>{pt(),Mt(),xt(),Z_=(e,r,t,s,i,n,o,a,l)=>{let d=[{type:12,data:n},{type:12,data:s},{type:12,data:i},{type:12,data:t},{type:12,data:o},{type:12,data:a},{type:12,data:l}],p=[n];d.push(...nt(r.dims,p));let u=h=>{let w=$e("indices_data",r.dataType,r.dims.length),f=tt("input_slice_offsets_data",12,1,1),P=[w,f],A=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${h.registerUniforms(A).declareVariables(...P)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1423,14 +1423,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); - }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d}),getShaderSource:u},{inputs:[r],outputs:[-1]})[0]},e_=(e,r)=>{let t=e.inputs,s=t[0].dims,i=t[0].dataType,n=t[1].dims,o=n[n.length-1],a=xe.sizeToDimension(n,n.length-1),l=xe.sizeFromDimension(s,r.batchDims+o),d=xe.sizeToDimension(s,r.batchDims),p=xe.sizeFromDimension(s,r.batchDims),u=a/d,h=new Array(o),w=l;for(let x=0;xs.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let A=n.slice(0,-1).concat(s.slice(P)),v=xe.size(A),y=[{type:12,data:v},{type:12,data:l},...nt(t[0].dims,_.dims,A)],S=x=>{let g=$e("data",t[0].dataType,t[0].dims.length),M=$e("slice_offsets",12,_.dims.length),E=tt("output",t[0].dataType,A.length);return` - ${x.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(g,M,E)} - ${x.mainStart()} - ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d}),getShaderSource:u},{inputs:[r],outputs:[-1]})[0]},ef=(e,r)=>{let t=e.inputs,s=t[0].dims,i=t[0].dataType,n=t[1].dims,o=n[n.length-1],a=xe.sizeToDimension(n,n.length-1),l=xe.sizeFromDimension(s,r.batchDims+o),d=xe.sizeToDimension(s,r.batchDims),p=xe.sizeFromDimension(s,r.batchDims),u=a/d,h=new Array(o),w=l;for(let T=0;Ts.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let A=n.slice(0,-1).concat(s.slice(P)),b=xe.size(A),y=[{type:12,data:b},{type:12,data:l},...nt(t[0].dims,f.dims,A)],$=T=>{let g=$e("data",t[0].dataType,t[0].dims.length),M=$e("slice_offsets",12,f.dims.length),E=tt("output",t[0].dataType,A.length);return` + ${T.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(g,M,E)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; - }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:A,dataType:i}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:y}),getShaderSource:S},{inputs:[t[0],_]})},t_=e=>({batchDims:e.batch_dims,cacheKey:""})}),r_,s_,n_,i_,mv=je(()=>{pt(),yt(),Yt(),vt(),r_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=xe.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,i=e[0],n=e[2],o=e.length===4?e[3]:void 0;if(n.dims.length!==i.dims.length||!i.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==n.dims.length||!o.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},s_=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=xe.normalizeAxis(r.gatherAxis,i),o=xe.normalizeAxis(r.quantizeAxis,i),a=t.slice(0);a.splice(n,1,...s);let l=xe.size(a),d=e[2].dataType,p=e[0].dataType===22,u=[{type:12,data:l},{type:12,data:o},{type:12,data:n},{type:12,data:r.blockSize},...nt(...e.map((w,_)=>w.dims),a)],h=w=>{let _=$e("data",e[0].dataType,e[0].dims.length),P=$e("inputIndices",e[1].dataType,e[1].dims.length),A=$e("scales",e[2].dataType,e[2].dims.length),v=e.length>3?$e("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=tt("output",d,a.length),S=[_,P,A];v&&S.push(v);let x=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${w.registerUniforms(x).declareVariables(...S,y)} + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:A,dataType:i}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:y}),getShaderSource:$},{inputs:[t[0],f]})},tf=e=>({batchDims:e.batch_dims,cacheKey:""})}),rf,sf,nf,of,Ev=Ue(()=>{pt(),Mt(),Yt(),xt(),rf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=xe.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,i=e[0],n=e[2],o=e.length===4?e[3]:void 0;if(n.dims.length!==i.dims.length||!i.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==n.dims.length||!o.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},sf=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=xe.normalizeAxis(r.gatherAxis,i),o=xe.normalizeAxis(r.quantizeAxis,i),a=t.slice(0);a.splice(n,1,...s);let l=xe.size(a),d=e[2].dataType,p=e[0].dataType===22,u=[{type:12,data:l},{type:12,data:o},{type:12,data:n},{type:12,data:r.blockSize},...nt(...e.map((w,f)=>w.dims),a)],h=w=>{let f=$e("data",e[0].dataType,e[0].dims.length),P=$e("inputIndices",e[1].dataType,e[1].dims.length),A=$e("scales",e[2].dataType,e[2].dims.length),b=e.length>3?$e("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=tt("output",d,a.length),$=[f,P,A];b&&$.push(b);let T=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${w.registerUniforms(T).declareVariables(...$,y)} ${w.mainStart()} let output_indices = ${y.offsetToIndices("global_idx")}; var indices_indices = ${P.type.indices}(0); @@ -1439,24 +1439,24 @@ fn main(@builtin(local_invocation_id) localId : vec3, let index = ${y.indicesGet("output_indices","uniforms.gather_axis + i")}; ${P.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${y.indicesGet("output_indices","uniforms.gather_axis")};`}; - var data_indices = ${_.type.indices}(0); + var data_indices = ${f.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${y.indicesGet("output_indices","i")}; - ${_.indicesSet("data_indices","i","index")}; + ${f.indicesSet("data_indices","i","index")}; } var index_from_indices = ${P.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${t[n]}; } - ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + ${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { let index = ${y.indicesGet("output_indices",`i + ${s.length} - 1`)}; - ${_.indicesSet("data_indices","i","index")}; + ${f.indicesSet("data_indices","i","index")}; } - let data_offset = ${_.indicesToOffset("data_indices")}; + let data_offset = ${f.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. - let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_4bit_quantized_data = ${f.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; @@ -1464,18 +1464,18 @@ fn main(@builtin(local_invocation_id) localId : vec3, let quantize_axis_index = ${A.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${A.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${A.getByIndices("scale_indices")}; - ${v?` + ${b?` let zero_point_indices = scale_indices; - let zero_point_offset = ${v.indicesToOffset("zero_point_indices")}; + let zero_point_offset = ${b.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; - let packed_4bit_zero_points = ${v.getByOffset("zero_point_offset / 8")}; + let packed_4bit_zero_points = ${b.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${Tr(d)}(quantized_data - zero_point) * scale; ${y.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((w,_)=>_!==1).map(w=>w.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(w,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:d}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:h}},n_=(e,r)=>{let t=e.inputs;r_(t,r),e.compute(s_(e.inputs,r))},i_=e=>Dt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),o_,a_,l_,d_,fv=je(()=>{pt(),yt(),Yt(),vt(),o_=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and - indices input tensors be of same rank.`)},a_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,i=t.length,n=e[1].dims,o=e[1].dataType,a=xe.normalizeAxis(r.axis,i),l=t[a],d=n.slice(0),p=xe.size(d),u=$e("input",s,i),h=$e("indicesInput",o,n.length),w=tt("output",s,d.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...nt(t,n,d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:P=>` + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((w,f)=>f!==1).map(w=>w.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(w,f)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:d}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:h}},nf=(e,r)=>{let t=e.inputs;rf(t,r),e.compute(sf(e.inputs,r))},of=e=>Dt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),af,lf,df,cf,Pv=Ue(()=>{pt(),Mt(),Yt(),xt(),af=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},lf=(e,r)=>{let t=e[0].dims,s=e[0].dataType,i=t.length,n=e[1].dims,o=e[1].dataType,a=xe.normalizeAxis(r.axis,i),l=t[a],d=n.slice(0),p=xe.size(d),u=$e("input",s,i),h=$e("indicesInput",o,n.length),w=tt("output",s,d.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return f.push(...nt(t,n,d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:P=>` ${P.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,w)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -1491,11 +1491,11 @@ fn main(@builtin(local_invocation_id) localId : vec3, let value = ${u.getByIndices("inputIndices")}; ${w.setByOffset("global_idx","value")}; - }`}},l_=e=>Dt({axis:e.axis}),d_=(e,r)=>{let t=e.inputs;o_(t),e.compute(a_(e.inputs,r))}}),c_,u_,p_,h_,_v=je(()=>{pt(),yt(),vt(),c_=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},u_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[i,n,o]=Fp.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[i,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,d=Math.ceil(n/l),p=Math.ceil(i/l),u=!0,h=xe.size(a),w=[{type:12,data:u?d:h},{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(w.push(...nt(e[2].dims)),_.push("rank")),w.push(...nt(a));let P=v=>{let y="";r.transA&&r.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",x=$e("a",e[0].dataType,e[0].dims),g=$e("b",e[1].dataType,e[1].dims),M=x.type.value,E=null,k=[x,g];e.length===3&&(E=$e("c",e[2].dataType,e[2].dims.length),k.push(E));let B=tt("output",e[0].dataType,a.length);k.push(B);let R=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` - ${v.registerUniforms(R).declareVariables(...k)} + }`}},df=e=>Dt({axis:e.axis}),cf=(e,r)=>{let t=e.inputs;af(t),e.compute(lf(e.inputs,r))}}),uf,pf,hf,mf,Cv=Ue(()=>{pt(),Mt(),xt(),uf=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},pf=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[i,n,o]=Op.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[i,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,d=Math.ceil(n/l),p=Math.ceil(i/l),u=!0,h=xe.size(a),w=[{type:12,data:u?d:h},{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(w.push(...nt(e[2].dims)),f.push("rank")),w.push(...nt(a));let P=b=>{let y="";r.transA&&r.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let $=r.alpha===1?"":"value *= uniforms.alpha;",T=$e("a",e[0].dataType,e[0].dims),g=$e("b",e[1].dataType,e[1].dims),M=T.type.value,E=null,k=[T,g];e.length===3&&(E=$e("c",e[2].dataType,e[2].dims.length),k.push(E));let B=tt("output",e[0].dataType,a.length);k.push(B);let N=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${b.registerUniforms(N).declareVariables(...k)} - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; @@ -1505,10 +1505,10 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${y} } - ${S} + ${$} ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",B)}; value += ${M}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} output[global_idx] = value; - }`},A=v=>{let y=$e("a",e[0].dataType,e[0].dims),S=$e("b",e[1].dataType,e[1].dims),x=null,g=[y,S];e.length===3&&(x=$e("c",e[2].dataType,e[2].dims.length),g.push(x));let M=tt("output",e[0].dataType,a.length);g.push(M);let E=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],k="",B="";r.transA&&r.transB?(B=` + }`},A=b=>{let y=$e("a",e[0].dataType,e[0].dims),$=$e("b",e[1].dataType,e[1].dims),T=null,g=[y,$];e.length===3&&(T=$e("c",e[2].dataType,e[2].dims.length),g.push(T));let M=tt("output",e[0].dataType,a.length);g.push(M);let E=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],k="",B="";r.transA&&r.transB?(B=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { @@ -1522,7 +1522,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { - tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); } `,k="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(B=` var col = tile_row_start + local_id.x; @@ -1538,7 +1538,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { - tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); } `,k="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(B=` var col = k_start + local_id.x; @@ -1554,7 +1554,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { - tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); } `,k="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(B=` var col = k_start + local_id.x; @@ -1570,13 +1570,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { - tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); } - `,k="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let R=r.alpha===1?"":"value *= uniforms.alpha;";return` - ${v.registerUniforms(E).declareVariables(...g)} + `,k="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let N=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${b.registerUniforms(E).declareVariables(...g)} var tile_a: array, ${l}>; - var tile_b: array, ${l}>; - ${v.mainStart([l,l,1])} + var tile_b: array, ${l}>; + ${b.mainStart([l,l,1])} let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; let num_tiles = (uniforms.K - 1) / ${l} + 1; @@ -1593,14 +1593,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, workgroupBarrier(); } - ${R} + ${N} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; - ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",M)}; value += ${M.type.value}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + ${T!=null?`let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)",M)}; value += ${M.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } - }`};return u?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:d*p},programUniforms:w}),getShaderSource:A}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:P}},p_=e=>{let r=e.transA,t=e.transB,s=e.alpha,i=e.beta;return{transA:r,transB:t,alpha:s,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},h_=(e,r)=>{c_(e.inputs),e.compute(u_(e.inputs,r))}}),vs,Is,Mn,bn,m_,f_,__,g_,w_,y_,M_,b_,v_,x_,gv=je(()=>{pt(),yt(),Yt(),vt(),[vs,Is,Mn,bn]=[0,1,2,3],m_=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},f_=` + }`};return u?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:d*p},programUniforms:w}),getShaderSource:A}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:P}},hf=e=>{let r=e.transA,t=e.transB,s=e.alpha,i=e.beta;return{transA:r,transB:t,alpha:s,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},mf=(e,r)=>{uf(e.inputs),e.compute(pf(e.inputs,r))}}),vs,Is,Mn,bn,_f,ff,gf,wf,yf,Mf,bf,vf,xf,Tf,Sv=Ue(()=>{pt(),Mt(),Yt(),xt(),[vs,Is,Mn,bn]=[0,1,2,3],_f=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},ff=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); @@ -1611,7 +1611,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } -`,__=e=>` +`,gf=e=>` fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); @@ -1622,7 +1622,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } -`,g_=e=>` +`,wf=e=>` fn gs_denormalize(n: f32, length: i32) -> f32 { ${e.alignCorners===0?` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] @@ -1632,7 +1632,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, return (n + 1.0) / 2.0 * (f32(length - 1)); `} } -`,w_=e=>` +`,yf=e=>` ${e.paddingMode==="reflection"?` fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { var dx = 0.0; @@ -1659,7 +1659,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, } return u32(fx); }`:""} -`,y_=(e,r,t)=>` +`,Mf=(e,r,t)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { var pixel = ${r}(0); var indices = vec4(0); @@ -1678,7 +1678,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } -`,M_=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` +`,bf=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${vs}], indices[${Is}], border); `;case"bilinear":return` let x1 = i32(floor(x)); @@ -1709,13 +1709,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); - `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,b_=(e,r)=>{let t=$e("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=$e("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[vs,Is,Mn,bn]=[0,3,1,2]);let o=tt("output",e[0].dataType,n.length),a=t.type.value,l=xe.size(n),d=[{type:12,data:l},...nt(e[0].dims,s,n)],p=u=>` + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,vf=(e,r)=>{let t=$e("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=$e("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[vs,Is,Mn,bn]=[0,3,1,2]);let o=tt("output",e[0].dataType,n.length),a=t.type.value,l=xe.size(n),d=[{type:12,data:l},...nt(e[0].dims,s,n)],p=u=>` ${u.registerUniform("output_size","u32").declareVariables(t,i,o)} - ${f_} - ${__(a)} - ${g_(r)} - ${w_(r)} - ${y_(t,a,r)} + ${ff} + ${gf(a)} + ${wf(r)} + ${yf(r)} + ${Mf(t,a,r)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1741,15 +1741,15 @@ fn main(@builtin(local_invocation_id) localId : vec3, var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); - ${M_(o,a,r)} - }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let h=xe.size(n);return{outputs:[{dims:n,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}},getShaderSource:p}},v_=(e,r)=>{m_(e.inputs),e.compute(b_(e.inputs,r))},x_=e=>Dt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),$r,T_,E_,gc,P_,Bi,C_,S_=je(()=>{pt(),yt(),Yt(),zd(),qd(),vt(),Gs(),$r=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,T_=(e,r)=>{let t=e[0],s=$r(e,1),i=$r(e,2),n=$r(e,3),o=$r(e,4),a=$r(e,5),l=$r(e,6),d=$r(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],u=t.dims[1],h=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],w=u,_=0,P=0,A=Math.floor(h/r.numHeads);if(l&&d&&xe.size(l.dims)&&xe.size(d.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==A)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[0]!==p||d.dims[1]!==r.numHeads||d.dims[3]!==A)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==d.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],P=l.dims[2]}else if(l&&xe.size(l.dims)||d&&xe.size(d.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(s&&xe.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');v=2,w=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==A)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');v=5,w=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==A)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');v=0,w=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}if(n&&xe.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=_+w,S=0;if(o&&xe.size(o.dims)>0){S=8;let E=o.dims;throw E.length===1?E[0]===p?S=1:E[0]===3*p+2&&(S=3):E.length===2&&E[0]===p&&E[1]===y&&(S=5),S===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let x=!1,g=h;if(i&&xe.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(w!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');g=i.dims[2]}else{if(w!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');g=i.dims[1]*i.dims[3],x=!0}}let M=!1;if(o&&xe.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(a&&xe.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==u||a.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:u,pastSequenceLength:_,kvSequenceLength:w,totalSequenceLength:y,maxSequenceLength:P,inputHiddenSize:0,hiddenSize:h,vHiddenSize:g,headSize:A,vHeadSize:Math.floor(g/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:M,passPastInKv:x,qkvFormat:v}},E_=e=>Dt({...e}),gc=Dt({perm:[0,2,1,3]}),P_=(e,r,t,s,i,n,o)=>{let a=[s,i,n],l=xe.size(a),d=[{type:12,data:l},{type:12,data:o},{type:12,data:n}],p=u=>{let h=tt("qkv_with_bias",r.dataType,a),w=$e("qkv",r.dataType,a),_=$e("bias",t.dataType,a),P=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${u.registerUniforms(P).declareVariables(w,_,h)} + ${bf(o,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let h=xe.size(n);return{outputs:[{dims:n,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}},getShaderSource:p}},xf=(e,r)=>{_f(e.inputs),e.compute(vf(e.inputs,r))},Tf=e=>Dt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),kr,Ef,Pf,wc,Cf,Bi,Sf,$f=Ue(()=>{pt(),Mt(),Yt(),Bd(),Qd(),xt(),Gs(),kr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Ef=(e,r)=>{let t=e[0],s=kr(e,1),i=kr(e,2),n=kr(e,3),o=kr(e,4),a=kr(e,5),l=kr(e,6),d=kr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],u=t.dims[1],h=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],w=u,f=0,P=0,A=Math.floor(h/r.numHeads);if(l&&d&&xe.size(l.dims)&&xe.size(d.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==A)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[0]!==p||d.dims[1]!==r.numHeads||d.dims[3]!==A)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==d.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],P=l.dims[2]}else if(l&&xe.size(l.dims)||d&&xe.size(d.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let b;if(s&&xe.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');b=2,w=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==A)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');b=5,w=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==A)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');b=0,w=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');b=3}if(n&&xe.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=f+w,$=0;if(o&&xe.size(o.dims)>0){$=8;let E=o.dims;throw E.length===1?E[0]===p?$=1:E[0]===3*p+2&&($=3):E.length===2&&E[0]===p&&E[1]===y&&($=5),$===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let T=!1,g=h;if(i&&xe.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(w!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');g=i.dims[2]}else{if(w!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');g=i.dims[1]*i.dims[3],T=!0}}let M=!1;if(o&&xe.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(a&&xe.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==u||a.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:u,pastSequenceLength:f,kvSequenceLength:w,totalSequenceLength:y,maxSequenceLength:P,inputHiddenSize:0,hiddenSize:h,vHiddenSize:g,headSize:A,vHeadSize:Math.floor(g/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:$,scale:r.scale,broadcastResPosBias:M,passPastInKv:T,qkvFormat:b}},Pf=e=>Dt({...e}),wc=Dt({perm:[0,2,1,3]}),Cf=(e,r,t,s,i,n,o)=>{let a=[s,i,n],l=xe.size(a),d=[{type:12,data:l},{type:12,data:o},{type:12,data:n}],p=u=>{let h=tt("qkv_with_bias",r.dataType,a),w=$e("qkv",r.dataType,a),f=$e("bias",t.dataType,a),P=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${u.registerUniforms(P).declareVariables(w,f,h)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; - }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Bi=(e,r,t,s,i,n,o,a)=>{let l=n;if(o&&xe.size(o.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=P_(e,n,o,r,s,t*i,a),l=l.reshape([r,s,t,i]),t===1||s===1?l:e.compute(Nr(l,gc.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,i])),t===1||s===1?l:e.compute(Nr(l,gc.perm),{inputs:[l],outputs:[-1]})[0]},C_=(e,r)=>{let t=T_(e.inputs,r),s=e.inputs[0],i=$r(e.inputs,1),n=$r(e.inputs,2),o=$r(e.inputs,3),a=$r(e.inputs,4),l=$r(e.inputs,5),d=$r(e.inputs,6),p=$r(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let u=i&&n&&i.dims.length===4&&n.dims.length===4,h=Bi(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,o,0);if(u)return Fi(e,h,i,n,a,void 0,d,p,l,t);if(!i||!n)throw new Error("key and value must be provided");let w=Bi(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,i,o,t.hiddenSize),_=Bi(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,o,2*t.hiddenSize);Fi(e,h,w,_,a,void 0,d,p,l,t)}}),$_,k_,I_,A_,wc,F_,O_,D_=je(()=>{pt(),yt(),Yt(),vt(),$_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},k_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>t.push(Number(i))),s=t.length),Dt({numOutputs:s,axis:r.axis,splitSizes:t})},I_=e=>` + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Bi=(e,r,t,s,i,n,o,a)=>{let l=n;if(o&&xe.size(o.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Cf(e,n,o,r,s,t*i,a),l=l.reshape([r,s,t,i]),t===1||s===1?l:e.compute(Nr(l,wc.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,i])),t===1||s===1?l:e.compute(Nr(l,wc.perm),{inputs:[l],outputs:[-1]})[0]},Sf=(e,r)=>{let t=Ef(e.inputs,r),s=e.inputs[0],i=kr(e.inputs,1),n=kr(e.inputs,2),o=kr(e.inputs,3),a=kr(e.inputs,4),l=kr(e.inputs,5),d=kr(e.inputs,6),p=kr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let u=i&&n&&i.dims.length===4&&n.dims.length===4,h=Bi(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,o,0);if(u)return Fi(e,h,i,n,a,void 0,d,p,l,t);if(!i||!n)throw new Error("key and value must be provided");let w=Bi(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,i,o,t.hiddenSize),f=Bi(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,o,2*t.hiddenSize);Fi(e,h,w,f,a,void 0,d,p,l,t)}}),kf,If,Af,Ff,yc,Of,Df,Lf=Ue(()=>{pt(),Mt(),Yt(),xt(),kf=e=>{if(!e||e.length<1)throw new Error("too few inputs")},If=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>t.push(Number(i))),s=t.length),Dt({numOutputs:s,axis:r.axis,splitSizes:t})},Af=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${rt("uniforms.size_in_split_axis","i",e)}) { @@ -1757,17 +1757,17 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return ${e}u; -}`,A_=e=>{let r=e.length,t=[];for(let s=0;s{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=xe.size(t),i=e[0].dataType,n=xe.normalizeAxis(r.axis,t.length),o=new Array(r.numOutputs),a=$e("input",i,t.length),l=new Array(r.numOutputs),d=[],p=[],u=0,h=[{type:12,data:s}];for(let _=0;_` - ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...o)} - ${I_(l.length)} - ${A_(o)} + }`},yc=(e,r)=>{let t=e[0].dims,s=xe.size(t),i=e[0].dataType,n=xe.normalizeAxis(r.axis,t.length),o=new Array(r.numOutputs),a=$e("input",i,t.length),l=new Array(r.numOutputs),d=[],p=[],u=0,h=[{type:12,data:s}];for(let f=0;f` + ${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...o)} + ${Af(l.length)} + ${Ff(o)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${a.offsetToIndices("global_idx")}; var index = ${a.indicesGet("indices",n)}; @@ -1777,7 +1777,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${a.indicesSet("indices",n,"index")}; } writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:h})}},F_=(e,r)=>{$_(e.inputs);let t=e.inputs.length===1?r:k_(e.inputs,r);e.compute(wc(e.inputs,t),{inputs:[0]})},O_=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Dt({axis:r,numOutputs:s,splitSizes:t})}}),L_,z_,yc,B_,wv=je(()=>{Yt(),qd(),S_(),D_(),Gs(),L_=(e,r)=>{if(r.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4];if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],d=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],u=d,h=0,w=!s||s.dims.length===0,_=Math.floor(w?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);w&&(p=_*r.numHeads);let P=n&&n.dims.length!==0,A=o&&o.dims.length!==0;if(P&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(P&&A){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=n.dims[2]}else if(P||A)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');u=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');u=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let y=0,S=!1,x=r.kvNumHeads?_*r.kvNumHeads:p;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(u!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');x=i.dims[2]}else{if(u!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');x=i.dims[1]*i.dims[3],S=!0}}let g=e.length>4?e[5]:void 0;if(g&&g.dims.length!==1&&g.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:d,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:x,headSize:_,vHeadSize:Math.floor(x/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:v}},z_=Dt({perm:[0,2,1,3]}),yc=(e,r,t)=>{let s=r,i=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,i,t.headSize]),s=e.compute(Nr(s,z_.perm),{inputs:[s],outputs:[-1]})[0]),s},B_=(e,r)=>{var A;let t=L_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((A=e.inputs[1])==null?void 0:A.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,d=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,u=Dt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[h,w,_]=!i&&!n?e.compute(wc([s],u),{inputs:[s],outputs:[-1,-1,-1]}):[s,i,n],P=Bi(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,h,void 0,0);Fi(e,P,yc(e,w,t),yc(e,_,t),void 0,void 0,o,a,void 0,t,l,d)}}),Mc,R_,N_,j_,yv=je(()=>{pt(),yt(),Gs(),vt(),Mc=(e,r,t,s,i,n,o,a)=>{let l=Xt(n),d=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,u=i*o,h=64;u===1&&(h=256);let w=[i,o,n/l],_=[i,o,2],P=["rank","type","type"],A=[];A.push(...nt(w,_));let v=y=>{let S=$e("x",r.dataType,3,l),x=$e("scale",t.dataType,t.dims),g=$e("bias",s.dataType,s.dims),M=tt("output",1,3,2),E=[S,x,g,M];return` + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:h})}},Of=(e,r)=>{kf(e.inputs);let t=e.inputs.length===1?r:If(e.inputs,r);e.compute(yc(e.inputs,t),{inputs:[0]})},Df=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Dt({axis:r,numOutputs:s,splitSizes:t})}}),zf,Bf,Mc,Rf,$v=Ue(()=>{Yt(),Qd(),$f(),Lf(),Gs(),zf=(e,r)=>{if(r.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4];if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],d=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],u=d,h=0,w=!s||s.dims.length===0,f=Math.floor(w?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);w&&(p=f*r.numHeads);let P=n&&n.dims.length!==0,A=o&&o.dims.length!==0;if(P&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===f)throw new Error("BSNH pastKey/pastValue is not supported");if(P&&A){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=n.dims[2]}else if(P||A)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let b=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');u=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==f)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');u=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==f)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');b=3}let y=0,$=!1,T=r.kvNumHeads?f*r.kvNumHeads:p;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(u!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=i.dims[2]}else{if(u!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=i.dims[1]*i.dims[3],$=!0}}let g=e.length>4?e[5]:void 0;if(g&&g.dims.length!==1&&g.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:d,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:T,headSize:f,vHeadSize:Math.floor(T/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:b}},Bf=Dt({perm:[0,2,1,3]}),Mc=(e,r,t)=>{let s=r,i=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,i,t.headSize]),s=e.compute(Nr(s,Bf.perm),{inputs:[s],outputs:[-1]})[0]),s},Rf=(e,r)=>{var A;let t=zf(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((A=e.inputs[1])==null?void 0:A.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,d=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,u=Dt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[h,w,f]=!i&&!n?e.compute(yc([s],u),{inputs:[s],outputs:[-1,-1,-1]}):[s,i,n],P=Bi(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,h,void 0,0);Fi(e,P,Mc(e,w,t),Mc(e,f,t),void 0,void 0,o,a,void 0,t,l,d)}}),bc,Nf,jf,Uf,kv=Ue(()=>{pt(),Mt(),Gs(),xt(),bc=(e,r,t,s,i,n,o,a)=>{let l=Xt(n),d=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,u=i*o,h=64;u===1&&(h=256);let w=[i,o,n/l],f=[i,o,2],P=["rank","type","type"],A=[];A.push(...nt(w,f));let b=y=>{let $=$e("x",r.dataType,3,l),T=$e("scale",t.dataType,t.dims),g=$e("bias",s.dataType,s.dims),M=tt("output",1,3,2),E=[$,T,g,M];return` var workgroup_shared : array<${p}, ${h}>; const workgroup_size = ${h}u; ${y.declareVariables(...E)} @@ -1789,7 +1789,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var sum = ${d}(0); var squared_sum = ${d}(0); for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${d}(${S.get("batch","channel","h")}); + let value = ${d}(${$.get("batch","channel","h")}); sum += value; squared_sum += value * value; } @@ -1811,59 +1811,59 @@ fn calculateOutputIndex(index: u32) -> u32 { let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } - }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${h}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:u},programUniforms:A}),getShaderSource:v},{inputs:[r,t,s],outputs:[-1]})[0]},R_=(e,r,t)=>{let s=r[0].dims,i=s,n=2,o=s[0],a=s[1],l=xe.sizeFromDimension(s,n),d=Xt(l),p=xe.size(i)/d,u=Mc(e,r[0],r[1],r[2],o,l,a,t.epsilon),h=[o,a,l/d],w=[o,a],_=["type","none"],P=A=>{let v=$e("x",r[0].dataType,h.length,d),y=$e("scale_shift",1,w.length,2),S=tt("output",r[0].dataType,h.length,d),x=[v,y,S];return` - ${A.registerUniform("output_size","u32").declareVariables(...x)} + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${h}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:u},programUniforms:A}),getShaderSource:b},{inputs:[r,t,s],outputs:[-1]})[0]},Nf=(e,r,t)=>{let s=r[0].dims,i=s,n=2,o=s[0],a=s[1],l=xe.sizeFromDimension(s,n),d=Xt(l),p=xe.size(i)/d,u=bc(e,r[0],r[1],r[2],o,l,a,t.epsilon),h=[o,a,l/d],w=[o,a],f=["type","none"],P=A=>{let b=$e("x",r[0].dataType,h.length,d),y=$e("scale_shift",1,w.length,2),$=tt("output",r[0].dataType,h.length,d),T=[b,y,$];return` + ${A.registerUniform("output_size","u32").declareVariables(...T)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${S.offsetToIndices("global_idx")}; + let outputIndices = ${$.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${y.getByIndices("vec2(batch, channel)")}; - let value = ${v.getByOffset("global_idx")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y); - ${S.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...nt(h,w,h)]}),getShaderSource:P},{inputs:[r[0],u]})},N_=(e,r,t)=>{let s=r[0].dims,i=s,n=s[0],o=s[s.length-1],a=xe.sizeFromDimension(s,1)/o,l=Xt(o),d=xe.size(i)/l,p=[{type:12,data:a},{type:12,data:Math.floor(o/l)}],u=["type","type"],h=!1,w=[0,s.length-1];for(let v=0;vs[w[y]])),P=Mc(e,_,r[1],r[2],n,a,o,t.epsilon),A=v=>{let y=lr(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,x=E=>{let k=E===0?"x":"y",B=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${y}(${B}(scale.${k}))`;case 2:return`vec2<${y}>(${B}(scale[0].${k}, scale[1].${k}))`;case 4:return`vec4<${y}>(${B}(scale[0].${k}, scale[1].${k}, scale[2].${k}, scale[3].${k}))`;default:throw new Error(`Not supported compoents ${l}`)}},g=$e("input",r[0].dataType,r[0].dims,l),M=tt("output",r[0].dataType,i,l);return` + let value = ${b.getByOffset("global_idx")} * ${$.type.value}(scale_shift.x) + ${$.type.value}(scale_shift.y); + ${$.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${d}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...nt(h,w,h)]}),getShaderSource:P},{inputs:[r[0],u]})},jf=(e,r,t)=>{let s=r[0].dims,i=s,n=s[0],o=s[s.length-1],a=xe.sizeFromDimension(s,1)/o,l=Xt(o),d=xe.size(i)/l,p=[{type:12,data:a},{type:12,data:Math.floor(o/l)}],u=["type","type"],h=!1,w=[0,s.length-1];for(let b=0;bs[w[y]])),P=bc(e,f,r[1],r[2],n,a,o,t.epsilon),A=b=>{let y=lr(r[0].dataType),$=l===1?"vec2f":`mat${l}x2f`,T=E=>{let k=E===0?"x":"y",B=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${y}(${B}(scale.${k}))`;case 2:return`vec2<${y}>(${B}(scale[0].${k}, scale[1].${k}))`;case 4:return`vec4<${y}>(${B}(scale[0].${k}, scale[1].${k}, scale[2].${k}, scale[3].${k}))`;default:throw new Error(`Not supported compoents ${l}`)}},g=$e("input",r[0].dataType,r[0].dims,l),M=tt("output",r[0].dataType,i,l);return` @group(0) @binding(0) var input : array<${g.type.storage}>; - @group(0) @binding(1) var scale_input : array<${S}>; + @group(0) @binding(1) var scale_input : array<${$}>; @group(0) @binding(2) var output : array<${M.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; - ${v.mainStart()} + ${b.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; - output[global_idx] = fma(input[global_idx], ${x(0)}, ${x(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:A},{inputs:[r[0],P]})},j_=(e,r)=>{r.format==="NHWC"?N_(e,e.inputs,r):R_(e,e.inputs,r)}}),U_,V_,W_,Mv=je(()=>{pt(),yt(),vt(),U_=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},V_=(e,r,t)=>{let s=r.simplified,i=e[0].dims,n=e[1],o=!s&&e[2],a=i,l=xe.normalizeAxis(r.axis,i.length),d=xe.sizeToDimension(i,l),p=xe.sizeFromDimension(i,l),u=xe.size(n.dims),h=o?xe.size(o.dims):0;if(u!==p||o&&h!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:A},{inputs:[r[0],P]})},Uf=(e,r)=>{r.format==="NHWC"?jf(e,e.inputs,r):Nf(e,e.inputs,r)}}),Vf,Wf,Gf,Iv=Ue(()=>{pt(),Mt(),xt(),Vf=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Wf=(e,r,t)=>{let s=r.simplified,i=e[0].dims,n=e[1],o=!s&&e[2],a=i,l=xe.normalizeAxis(r.axis,i.length),d=xe.sizeToDimension(i,l),p=xe.sizeFromDimension(i,l),u=xe.size(n.dims),h=o?xe.size(o.dims):0;if(u!==p||o&&h!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. Size of scale and bias (if provided) must match this. - Got scale size of ${u} and bias size of ${h}`);let w=[];for(let g=0;g1,y=t>2,S=g=>{let M=lr(e[0].dataType),E=[$e("x",e[0].dataType,e[0].dims,_),$e("scale",n.dataType,n.dims,_)];o&&E.push($e("bias",o.dataType,o.dims,_)),E.push(tt("output",e[0].dataType,a,_)),v&&E.push(tt("mean_data_output",1,w)),y&&E.push(tt("inv_std_output",1,w));let k=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + Got scale size of ${u} and bias size of ${h}`);let w=[];for(let g=0;g1,y=t>2,$=g=>{let M=lr(e[0].dataType),E=[$e("x",e[0].dataType,e[0].dims,f),$e("scale",n.dataType,n.dims,f)];o&&E.push($e("bias",o.dataType,o.dims,f)),E.push(tt("output",e[0].dataType,a,f)),b&&E.push(tt("mean_data_output",1,w)),y&&E.push(tt("inv_std_output",1,w));let k=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${g.registerUniforms(k).declareVariables(...E)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${jd("f32",_)}; - var mean_square_vector = ${jd("f32",_)}; + var mean_vector = ${Ud("f32",f)}; + var mean_square_vector = ${Ud("f32",f)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${Un(M,_,"x[h + offset]")}; + let value = ${Un(M,f,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } - let mean = ${Ws("mean_vector",_)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Ws("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + let mean = ${Ws("mean_vector",f)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Ws("mean_square_vector",f)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { - let f32input = ${Un(M,_,"x[j + offset]")}; - let f32scale = ${Un(M,_,"scale[j]")}; + let f32input = ${Un(M,f,"x[j + offset]")}; + let f32scale = ${Un(M,f,"scale[j]")}; output[j + offset] = ${E[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale - ${o?`+ ${Un(M,_,"bias[j]")}`:""} + ${o?`+ ${Un(M,f,"bias[j]")}`:""} ); } - ${v?"mean_data_output[global_idx] = mean":""}; + ${b?"mean_data_output[global_idx] = mean":""}; ${y?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},x=[{dims:a,dataType:e[0].dataType}];return v&&x.push({dims:w,dataType:1}),y&&x.push({dims:w,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:P},getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(d/64)},programUniforms:A}),getShaderSource:S}},W_=(e,r)=>{U_(e.inputs),e.compute(V_(e.inputs,r,e.outputCount))}}),G_,K_,bv=je(()=>{yt(),rc(),oc(),G_=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},K_=e=>{G_(e.inputs);let r=Nn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(tc(e.inputs,{activation:""},r));else{let i=r[r.length-2],n=xe.size(e.inputs[0].dims.slice(0,-2)),o=xe.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&i===1&&o===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),d=[1,n,t],p=[a,l];e.compute(Ca(p,{activation:""},r,d),{inputs:p})}else e.compute(Ca(e.inputs,{activation:""},r))}}}),H_,q_,Q_,X_,J_,vv=je(()=>{pt(),yt(),Yt(),vt(),H_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,o=e[1];if(!xe.areEqual(o.dims,[r.n,i,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(xe.size(a)!==r.n*i)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,d=r.bits>4?r.n*i:r.n*Math.floor((i+1)/2);if(xe.size(l)!==d)throw new Error("zeroPoints input size error.")}},q_=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=xe.size(a),d=e[1].dims[2]/4,p=e[0].dataType,u=Xt(r.k),h=Xt(d),w=Xt(o),_=a.concat([i,o]),P=i>1&&o/w%2===0?2:1,A=xe.size(_)/w/P,v=64,y=[],S=[l,i,n/u],x=xe.convertShape(e[1].dims).slice();x.splice(-1,1,d/h),y.push(...nt(S)),y.push(...nt(x)),y.push(...nt(e[2].dims)),e.length===4&&y.push(...nt(xe.convertShape(e[3].dims)));let g=[l,i,o/w];y.push(...nt(g));let M=E=>{let k=S.length,B=$e("a",e[0].dataType,k,u),R=$e("b",12,x.length,h),J=$e("scales",e[2].dataType,e[2].dims.length),q=[B,R,J],V=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;V&&q.push(V);let Y=g.length,H=tt("output",e[0].dataType,Y,w),Q=lr(e[0].dataType),ie=(()=>{switch(u){case 1:return`array<${Q}, 8>`;case 2:return`mat4x2<${Q}>`;case 4:return`mat2x4<${Q}>`;default:throw new Error(`${u}-component is not supported.`)}})(),le=()=>{let N=` + }`},T=[{dims:a,dataType:e[0].dataType}];return b&&T.push({dims:w,dataType:1}),y&&T.push({dims:w,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:P},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/64)},programUniforms:A}),getShaderSource:$}},Gf=(e,r)=>{Vf(e.inputs),e.compute(Wf(e.inputs,r,e.outputCount))}}),Kf,Hf,Av=Ue(()=>{Mt(),sc(),ac(),Kf=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Hf=e=>{Kf(e.inputs);let r=Nn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(rc(e.inputs,{activation:""},r));else{let i=r[r.length-2],n=xe.size(e.inputs[0].dims.slice(0,-2)),o=xe.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&i===1&&o===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),d=[1,n,t],p=[a,l];e.compute(Ca(p,{activation:""},r,d),{inputs:p})}else e.compute(Ca(e.inputs,{activation:""},r))}}}),qf,Qf,Xf,Jf,Yf,Fv=Ue(()=>{pt(),Mt(),Yt(),xt(),qf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,o=e[1];if(!xe.areEqual(o.dims,[r.n,i,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(xe.size(a)!==r.n*i)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,d=r.bits>4?r.n*i:r.n*Math.floor((i+1)/2);if(xe.size(l)!==d)throw new Error("zeroPoints input size error.")}},Qf=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=xe.size(a),d=e[1].dims[2]/4,p=e[0].dataType,u=Xt(r.k),h=Xt(d),w=Xt(o),f=a.concat([i,o]),P=i>1&&o/w%2===0?2:1,A=xe.size(f)/w/P,b=64,y=[],$=[l,i,n/u],T=xe.convertShape(e[1].dims).slice();T.splice(-1,1,d/h),y.push(...nt($)),y.push(...nt(T)),y.push(...nt(e[2].dims)),e.length===4&&y.push(...nt(xe.convertShape(e[3].dims)));let g=[l,i,o/w];y.push(...nt(g));let M=E=>{let k=$.length,B=$e("a",e[0].dataType,k,u),N=$e("b",12,T.length,h),J=$e("scales",e[2].dataType,e[2].dims.length),q=[B,N,J],V=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;V&&q.push(V);let Y=g.length,H=tt("output",e[0].dataType,Y,w),Q=lr(e[0].dataType),ie=(()=>{switch(u){case 1:return`array<${Q}, 8>`;case 2:return`mat4x2<${Q}>`;case 4:return`mat2x4<${Q}>`;default:throw new Error(`${u}-component is not supported.`)}})(),le=()=>{let R=` // reuse a data var input_offset = ${B.indicesToOffset(`${B.type.indices}(batch, row, word_offset)`)}; var a_data: ${ie}; @@ -1871,14 +1871,14 @@ fn calculateOutputIndex(index: u32) -> u32 { a_data[j] = ${B.getByOffset("input_offset")}; input_offset++; } - `;for(let O=0;O> 4) & b_mask); b_quantized_values = ${ie}(${Array.from({length:4},(G,ne)=>`${Q}(b_value_lower[${ne}]), ${Q}(b_value_upper[${ne}])`).join(", ")}); b_dequantized_values = ${u===1?`${ie}(${Array.from({length:8},(G,ne)=>`(b_quantized_values[${ne}] - ${V?`zero_point${O}`:"zero_point"}) * scale${O}`).join(", ")});`:`(b_quantized_values - ${ie}(${Array(8).fill(`${V?`zero_point${O}`:"zero_point"}`).join(",")})) * scale${O};`}; workgroup_shared[local_id.x * ${P} + ${Math.floor(O/w)}]${w>1?`[${O%w}]`:""} += ${Array.from({length:8/u},(G,ne)=>`${u===1?`a_data[${ne}] * b_dequantized_values[${ne}]`:`dot(a_data[${ne}], b_dequantized_values[${ne}])`}`).join(" + ")}; - `;return N},ae=()=>{let N=` + `;return R},ae=()=>{let R=` var col_index = col * ${w}; ${V?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; @@ -1890,7 +1890,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${Q}(8);`} - `;for(let O=0;O> 0x1u); @@ -1899,30 +1899,30 @@ fn calculateOutputIndex(index: u32) -> u32 { zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${V.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${O} = ${Q}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return N},ge=()=>{let N=`col_index = col * ${w};`;for(let O=0;O{let R=`col_index = col * ${w};`;for(let O=0;O; var b_value_upper: vec4; var b_quantized_values: ${ie}; - var b_dequantized_values: ${ie};`,N};return` - var workgroup_shared: array<${H.type.value}, ${P*v}>; + var b_dequantized_values: ${ie};`,R};return` + var workgroup_shared: array<${H.type.value}, ${P*b}>; ${E.declareVariables(...q,H)} - ${E.mainStart([v,1,1])} - let output_indices = ${H.offsetToIndices(`(global_idx / ${v}) * ${P}`)}; + ${E.mainStart([b,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${b}) * ${P}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; - for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) { + for (var block = local_id.x; block < nBlocksPerCol; block += ${b}) { //process one block var word_offset: u32 = block * ${r.blockSize/u}; ${ae()} for (var word: u32 = 0; word < ${d}; word += ${h}) { - ${ge()} + ${we()} for (var i: u32 = 0; i < ${h}; i++) { ${le()} word_offset += ${8/u}; @@ -1934,13 +1934,13 @@ fn calculateOutputIndex(index: u32) -> u32 { if (local_id.x < ${P}) { var output_value: ${H.type.value} = ${H.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; - for (var b: u32 = 0u; b < ${v}u; b++) { + for (var b: u32 = 0u; b < ${b}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${P}; } ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${u};${h};${w};${P};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:A},programUniforms:y}),getShaderSource:M}},Q_=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=xe.size(a),d=e[1].dims[2]/4,p=e[0].dataType,u=Xt(r.k),h=Xt(d),w=a.concat([i,o]),_=128,P=o%8===0?8:o%4===0?4:1,A=_/P,v=A*h*8,y=v/u,S=v/r.blockSize,x=xe.size(w)/P,g=[],M=[l,i,n/u],E=xe.convertShape(e[1].dims).slice();E.splice(-1,1,d/h),g.push(...nt(M)),g.push(...nt(E)),g.push(...nt(e[2].dims)),e.length===4&&g.push(...nt(xe.convertShape(e[3].dims)));let k=[l,i,o];g.push(...nt(k));let B=R=>{let J=M.length,q=$e("a",e[0].dataType,J,u),V=$e("b",12,E.length,h),Y=$e("scales",e[2].dataType,e[2].dims.length),H=[q,V,Y],Q=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;Q&&H.push(Q);let ie=k.length,le=tt("output",e[0].dataType,ie),ae=lr(e[0].dataType),ge=()=>{switch(u){case 1:return` + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${u};${h};${w};${P};${b}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:A},programUniforms:y}),getShaderSource:M}},Xf=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=xe.size(a),d=e[1].dims[2]/4,p=e[0].dataType,u=Xt(r.k),h=Xt(d),w=a.concat([i,o]),f=128,P=o%8===0?8:o%4===0?4:1,A=f/P,b=A*h*8,y=b/u,$=b/r.blockSize,T=xe.size(w)/P,g=[],M=[l,i,n/u],E=xe.convertShape(e[1].dims).slice();E.splice(-1,1,d/h),g.push(...nt(M)),g.push(...nt(E)),g.push(...nt(e[2].dims)),e.length===4&&g.push(...nt(xe.convertShape(e[3].dims)));let k=[l,i,o];g.push(...nt(k));let B=N=>{let J=M.length,q=$e("a",e[0].dataType,J,u),V=$e("b",12,E.length,h),Y=$e("scales",e[2].dataType,e[2].dims.length),H=[q,V,Y],Q=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;Q&&H.push(Q);let ie=k.length,le=tt("output",e[0].dataType,ie),ae=lr(e[0].dataType),we=()=>{switch(u){case 1:return` let a_data0 = vec4<${ae}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${ae}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${ae}>(sub_a[word_offset], sub_a[word_offset + 1]); @@ -1949,20 +1949,20 @@ fn calculateOutputIndex(index: u32) -> u32 { let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${u}-component is not supported.`)}};return` var sub_a: array<${q.type.value}, ${y}>; var inter_results: array, ${P}>; - ${R.declareVariables(...H,le)} - ${R.mainStart([A,P,1])} + ${N.declareVariables(...H,le)} + ${N.mainStart([A,P,1])} let output_indices = ${le.offsetToIndices(`workgroup_index * ${P}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let n_blocks_per_col = uniforms.b_shape[1]; - let num_tiles = (n_blocks_per_col - 1) / ${S} + 1; + let num_tiles = (n_blocks_per_col - 1) / ${$} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${y}; // load one tile A data into shared memory. - for (var a_offset = local_idx; a_offset < ${y}; a_offset += ${_}) + for (var a_offset = local_idx; a_offset < ${y}; a_offset += ${f}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) @@ -1976,7 +1976,7 @@ fn calculateOutputIndex(index: u32) -> u32 { // each thread process one block let b_row = col + local_id.y; - let block = tile * ${S} + local_id.x; + let block = tile * ${$} + local_id.x; ${Q?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); @@ -1992,13 +1992,13 @@ fn calculateOutputIndex(index: u32) -> u32 { let b_data = ${V.getByIndices(`${V.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${r.blockSize/u}; for (var i: u32 = 0; i < ${h}; i++) { - ${ge()} + ${we()} let b_value = ${h===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); - let b_quantized_values = mat2x4<${ae}>(${Array.from({length:4},(N,O)=>`${ae}(b_value_lower[${O}]), ${ae}(b_value_upper[${O}])`).join(", ")}); + let b_quantized_values = mat2x4<${ae}>(${Array.from({length:4},(R,O)=>`${ae}(b_value_lower[${O}]), ${ae}(b_value_upper[${O}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${ae}>(${Array(8).fill("zero_point").join(",")})) * scale; - inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(N,O)=>`${`dot(a_data${O}, b_dequantized_values[${O}])`}`).join(" + ")}; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(R,O)=>`${`dot(a_data${O}, b_dequantized_values[${O}])`}`).join(" + ")}; word_offset += ${8/u}; } workgroupBarrier(); @@ -2014,7 +2014,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${le.setByIndices(`${le.type.indices}(batch, row, col + local_idx)`,"output_value")} } } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${u};${h};${A};${P}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:w,dataType:p}],dispatchGroup:{x},programUniforms:g}),getShaderSource:B}},X_=(e,r)=>{H_(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Q_(e.inputs,r)):e.compute(q_(e.inputs,r))},J_=e=>Dt(e)}),Y_,Z_,eg,tg,rg,sg,ng,ig,og,xv=je(()=>{pt(),yt(),vt(),Y_=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Z_=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${u};${h};${A};${P}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:w,dataType:p}],dispatchGroup:{x:T},programUniforms:g}),getShaderSource:B}},Jf=(e,r)=>{qf(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Xf(e.inputs,r)):e.compute(Qf(e.inputs,r))},Yf=e=>Dt(e)}),Zf,eg,tg,rg,sg,ng,ig,og,ag,Ov=Ue(()=>{pt(),Mt(),xt(),Zf=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},eg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; if (k < 0) { break; @@ -2031,7 +2031,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${s} value = x[offset]; } - `},eg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + `},tg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; if (k < 0) { k = -k; @@ -2049,7 +2049,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${s} value = x[offset]; - `},tg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + `},rg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; if (k < 0) { k = 0; @@ -2063,7 +2063,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${s} value = x[offset]; - `},rg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + `},sg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; if (k < 0) { k += i32(${rt("uniforms.x_shape",i,r)}]); @@ -2077,8 +2077,8 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${s} value = x[offset]; - `},sg=(e,r,t)=>{switch(t.mode){case 0:return Z_(e,r,t.pads.length);case 1:return eg(e,r,t.pads.length);case 2:return tg(e,r,t.pads.length);case 3:return rg(e,r,t.pads.length);default:throw new Error("Invalid mode")}},ng=(e,r)=>{let t=xe.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,i=xe.size(t),n=[{type:12,data:i},{type:6,data:r.pads}],o=e.length>=3&&e[2].data;r.mode===0&&n.push({type:o?e[2].dataType:1,data:r.value}),n.push(...nt(e[0].dims,t));let a=["rank"],l=d=>{let p=tt("output",e[0].dataType,t.length),u=$e("x",e[0].dataType,s.length),h=u.type.value,w=sg(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:o?h:"f32"}),` - ${d.registerUniforms(_).declareVariables(u,p)} + `},ng=(e,r,t)=>{switch(t.mode){case 0:return eg(e,r,t.pads.length);case 1:return tg(e,r,t.pads.length);case 2:return rg(e,r,t.pads.length);case 3:return sg(e,r,t.pads.length);default:throw new Error("Invalid mode")}},ig=(e,r)=>{let t=xe.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,i=xe.size(t),n=[{type:12,data:i},{type:6,data:r.pads}],o=e.length>=3&&e[2].data;r.mode===0&&n.push({type:o?e[2].dataType:1,data:r.value}),n.push(...nt(e[0].dims,t));let a=["rank"],l=d=>{let p=tt("output",e[0].dataType,t.length),u=$e("x",e[0].dataType,s.length),h=u.type.value,w=ng(p,s.length,r),f=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&f.push({name:"constant_value",type:o?h:"f32"}),` + ${d.registerUniforms(f).declareVariables(u,p)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -2087,7 +2087,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var value = ${h}(0); ${w} output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${o}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(xe.size(t)/64)},programUniforms:n}),getShaderSource:l}},ig=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,n=new Int32Array(2*i).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let o=[];return n.forEach(a=>o.push(a)),{mode:r.mode,value:s,pads:o}}else return r},og=(e,r)=>{Y_(e.inputs);let t=ig(e.inputs,r);e.compute(ng(e.inputs,t),{inputs:[0]})}}),Ri,bc,vc,xc,Tc,ag,lg,Ec,Pc,dg,cg,Cc,ug,pg,Sc,hg,mg,fg,_g,Tv=je(()=>{ss(),pt(),yt(),vt(),Ri=e=>{if(Vt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},bc=(e,r,t)=>{let s=r.format==="NHWC",i=e.dims.slice();s&&i.splice(1,0,i.pop());let n=Object.hasOwnProperty.call(r,"dilations"),o=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],d=r.pads.slice();va.adjustPoolAttributes(t,i,o,a,l,d);let p=va.computePoolOutputShape(t,i,a,l,o,d,r.autoPad),u=Object.assign({},r);n?Object.assign(u,{kernelShape:o,strides:a,pads:d,dilations:l,cacheKey:r.cacheKey}):Object.assign(u,{kernelShape:o,strides:a,pads:d,cacheKey:r.cacheKey});let h=p.slice();return h.push(h.splice(1,1)[0]),[u,s?h:p]},vc=(e,r)=>{let t=r.format==="NHWC",s=xe.size(e),i=xe.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],d=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],u=!!(d+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:d},{type:12,data:p}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(r.kernelShape.length===2){let w=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],P=r.pads[r.pads.length/2-2],A=r.pads[r.pads.length-2];h=!!(P+A),n.push({type:12,data:w},{type:12,data:_},{type:12,data:P},{type:12,data:A}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,o,!0,u,h]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=xe.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),o.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((d,p)=>d+p);return[n,o,!!l,!1,!1]}},xc=(e,r,t,s,i,n,o,a,l,d,p,u)=>{let h=i.format==="NHWC",w=r.type.value,_=tt("output",r.type.tensor,s);if(i.kernelShape.length<=2){let P="",A="",v="",y=t-(h?2:1);if(p?P=` + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${o}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(xe.size(t)/64)},programUniforms:n}),getShaderSource:l}},og=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,n=new Int32Array(2*i).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let o=[];return n.forEach(a=>o.push(a)),{mode:r.mode,value:s,pads:o}}else return r},ag=(e,r)=>{Zf(e.inputs);let t=og(e.inputs,r);e.compute(ig(e.inputs,t),{inputs:[0]})}}),Ri,vc,xc,Tc,Ec,lg,dg,Pc,Cc,cg,ug,Sc,pg,hg,$c,mg,_g,fg,gg,Dv=Ue(()=>{ss(),pt(),Mt(),xt(),Ri=e=>{if(Vt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},vc=(e,r,t)=>{let s=r.format==="NHWC",i=e.dims.slice();s&&i.splice(1,0,i.pop());let n=Object.hasOwnProperty.call(r,"dilations"),o=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],d=r.pads.slice();va.adjustPoolAttributes(t,i,o,a,l,d);let p=va.computePoolOutputShape(t,i,a,l,o,d,r.autoPad),u=Object.assign({},r);n?Object.assign(u,{kernelShape:o,strides:a,pads:d,dilations:l,cacheKey:r.cacheKey}):Object.assign(u,{kernelShape:o,strides:a,pads:d,cacheKey:r.cacheKey});let h=p.slice();return h.push(h.splice(1,1)[0]),[u,s?h:p]},xc=(e,r)=>{let t=r.format==="NHWC",s=xe.size(e),i=xe.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],d=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],u=!!(d+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:d},{type:12,data:p}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(r.kernelShape.length===2){let w=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],P=r.pads[r.pads.length/2-2],A=r.pads[r.pads.length-2];h=!!(P+A),n.push({type:12,data:w},{type:12,data:f},{type:12,data:P},{type:12,data:A}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,o,!0,u,h]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=xe.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),o.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((d,p)=>d+p);return[n,o,!!l,!1,!1]}},Tc=(e,r,t,s,i,n,o,a,l,d,p,u)=>{let h=i.format==="NHWC",w=r.type.value,f=tt("output",r.type.tensor,s);if(i.kernelShape.length<=2){let P="",A="",b="",y=t-(h?2:1);if(p?P=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${y}] < 0 || xIndices[${y}] @@ -2102,36 +2102,36 @@ fn calculateOutputIndex(index: u32) -> u32 { xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${r.indicesToOffset("xIndices")}]; ${n} - }`,i.kernelShape.length===2){let S=t-(h?3:2);u?A=` + }`,i.kernelShape.length===2){let $=t-(h?3:2);u?A=` for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; - if (xIndices[${S}] < 0 || xIndices[${S}] >= uniforms.x_shape[${S}]) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${$}] < 0 || xIndices[${$}] >= uniforms.x_shape[${$}]) { pad += i32(uniforms.kw); continue; } `:A=` for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; - `,v=` + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + `,b=` } `}return` - ${e.registerUniforms(l).declareVariables(r,_)} + ${e.registerUniforms(l).declareVariables(r,f)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${_.offsetToIndices("global_idx")}; - var xIndices = ${_.offsetToIndices("global_idx")}; + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; var value = ${w}(${a}); var pad = 0; ${A} ${P} - ${v} + ${b} ${o} output[global_idx] = value; - }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let P=i.kernelShape.length,A=i.pads.length,v="";return d?v=` + }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let P=i.kernelShape.length,A=i.pads.length,b="";return d?b=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; @@ -2141,17 +2141,17 @@ fn calculateOutputIndex(index: u32) -> u32 { if (!isPad) { let x_val = x[${r.indicesToOffset("xIndices")}]; ${n} - }`:v=` + }`:b=` } let x_val = x[${r.indicesToOffset("xIndices")}]; ${n} `,` - ${e.registerUniforms(l).declareVariables(r,_)} + ${e.registerUniforms(l).declareVariables(r,f)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${_.offsetToIndices("global_idx")}; - var xIndices = ${_.offsetToIndices("global_idx")}; + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; var offsets: array; @@ -2171,14 +2171,14 @@ fn calculateOutputIndex(index: u32) -> u32 { for (var j = ${t-P}u; j < ${t}u; j++) { xIndices[j] = indices[j] * ${rt("uniforms.strides",`j - ${t-P}u`,P)} + offsets[j - ${t-P}u] - ${rt("uniforms.pads","j - 2u",A)}; - ${v} + ${b} } ${o} output[global_idx] = value; - }`}},Tc=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,ag=e=>`${Tc(e)};${e.countIncludePad}`,lg=e=>`${Tc(e)};${e.storageOrder};${e.dilations}`,Ec=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Pc=(e,r,t,s)=>{let[i,n]=bc(r,s,t),o=$e("x",r.dataType,r.dims.length),a=o.type.value,l="value += x_val;",d="";i.countIncludePad?d+=`value /= ${a}(uniforms.kernelSize);`:d+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,u,h,w,_]=vc(n,i);p.push(...nt(r.dims,n));let P=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${h};${w};${_}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(xe.size(n)/64)},programUniforms:p}),getShaderSource:A=>xc(A,o,r.dims.length,n.length,i,l,d,0,u,h,w,_)}},dg=e=>{let r=e.count_include_pad!==0,t=Ec(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:ag(s)}},cg=(e,r)=>{Ri(e.inputs),e.compute(Pc("AveragePool",e.inputs[0],!1,r))},Cc={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ug=e=>{let r=e.format;return{format:r,...Cc,cacheKey:r}},pg=(e,r)=>{Ri(e.inputs),e.compute(Pc("GlobalAveragePool",e.inputs[0],!0,r))},Sc=(e,r,t,s)=>{let[i,n]=bc(r,s,t),o=` + }`}},Ec=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,lg=e=>`${Ec(e)};${e.countIncludePad}`,dg=e=>`${Ec(e)};${e.storageOrder};${e.dilations}`,Pc=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Cc=(e,r,t,s)=>{let[i,n]=vc(r,s,t),o=$e("x",r.dataType,r.dims.length),a=o.type.value,l="value += x_val;",d="";i.countIncludePad?d+=`value /= ${a}(uniforms.kernelSize);`:d+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,u,h,w,f]=xc(n,i);p.push(...nt(r.dims,n));let P=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${h};${w};${f}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(xe.size(n)/64)},programUniforms:p}),getShaderSource:A=>Tc(A,o,r.dims.length,n.length,i,l,d,0,u,h,w,f)}},cg=e=>{let r=e.count_include_pad!==0,t=Pc(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:lg(s)}},ug=(e,r)=>{Ri(e.inputs),e.compute(Cc("AveragePool",e.inputs[0],!1,r))},Sc={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},pg=e=>{let r=e.format;return{format:r,...Sc,cacheKey:r}},hg=(e,r)=>{Ri(e.inputs),e.compute(Cc("GlobalAveragePool",e.inputs[0],!0,r))},$c=(e,r,t,s)=>{let[i,n]=vc(r,s,t),o=` value = max(x_val, value); - `,a="",l=$e("x",r.dataType,r.dims.length),d=["rank"],[p,u,h,w,_]=vc(n,i);return p.push(...nt(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${h};${w};${_}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(xe.size(n)/64)},programUniforms:p}),getShaderSource:P=>xc(P,l,r.dims.length,n.length,i,o,a,r.dataType===10?-65504:-1e5,u,h,w,_)}},hg=(e,r)=>{Ri(e.inputs),e.compute(Sc("MaxPool",e.inputs[0],!1,r))},mg=e=>{let r=e.storage_order,t=e.dilations,s=Ec(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:r,dilations:t,...s,cacheKey:""};return{...i,cacheKey:lg(i)}},fg=e=>{let r=e.format;return{format:r,...Cc,cacheKey:r}},_g=(e,r)=>{Ri(e.inputs),e.compute(Sc("GlobalMaxPool",e.inputs[0],!0,r))}}),gg,wg,yg,Mg,Ev=je(()=>{pt(),yt(),Yt(),vt(),gg=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,n)=>n===r.axis||i===e[0].dims[n]).reduce((i,n)=>i&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},wg=(e,r)=>{let t=xe.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,i=s===3,n=e[0].dims,o=e[1].dataType,a=xe.size(n),l=s===3||s===2,d=l?[Math.ceil(xe.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,u=e.length>2?e[2]:void 0,h=u?l?[Math.ceil(xe.size(u.dims)/4)]:u.dims:void 0,w=p.length===0||p.length===1&&p[0]===1,_=w===!1&&p.length===1,P=Xt(a),A=w&&(!l||P===4),v=A?P:1,y=A&&!l?P:1,S=$e("input",l?12:s,d.length,y),x=$e("scale",o,p.length),g=u?$e("zero_point",l?12:s,h.length):void 0,M=tt("output",o,n.length,v),E=[S,x];g&&E.push(g);let k=[d,p];u&&k.push(h);let B=[{type:12,data:a/v},{type:12,data:t},{type:12,data:r.blockSize},...nt(...k,n)],R=J=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + `,a="",l=$e("x",r.dataType,r.dims.length),d=["rank"],[p,u,h,w,f]=xc(n,i);return p.push(...nt(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${h};${w};${f}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(xe.size(n)/64)},programUniforms:p}),getShaderSource:P=>Tc(P,l,r.dims.length,n.length,i,o,a,r.dataType===10?-65504:-1e5,u,h,w,f)}},mg=(e,r)=>{Ri(e.inputs),e.compute($c("MaxPool",e.inputs[0],!1,r))},_g=e=>{let r=e.storage_order,t=e.dilations,s=Pc(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:r,dilations:t,...s,cacheKey:""};return{...i,cacheKey:dg(i)}},fg=e=>{let r=e.format;return{format:r,...Sc,cacheKey:r}},gg=(e,r)=>{Ri(e.inputs),e.compute($c("GlobalMaxPool",e.inputs[0],!0,r))}}),wg,yg,Mg,bg,Lv=Ue(()=>{pt(),Mt(),Yt(),xt(),wg=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,n)=>n===r.axis||i===e[0].dims[n]).reduce((i,n)=>i&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},yg=(e,r)=>{let t=xe.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,i=s===3,n=e[0].dims,o=e[1].dataType,a=xe.size(n),l=s===3||s===2,d=l?[Math.ceil(xe.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,u=e.length>2?e[2]:void 0,h=u?l?[Math.ceil(xe.size(u.dims)/4)]:u.dims:void 0,w=p.length===0||p.length===1&&p[0]===1,f=w===!1&&p.length===1,P=Xt(a),A=w&&(!l||P===4),b=A?P:1,y=A&&!l?P:1,$=$e("input",l?12:s,d.length,y),T=$e("scale",o,p.length),g=u?$e("zero_point",l?12:s,h.length):void 0,M=tt("output",o,n.length,b),E=[$,T];g&&E.push(g);let k=[d,p];u&&k.push(h);let B=[{type:12,data:a/b},{type:12,data:t},{type:12,data:r.blockSize},...nt(...k,n)],N=J=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${J.registerUniforms(q).declareVariables(...E,M)} ${J.mainStart()} ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -2186,42 +2186,42 @@ fn calculateOutputIndex(index: u32) -> u32 { // Set input x ${l?` - let input = ${S.getByOffset("global_idx / 4")}; + let input = ${$.getByOffset("global_idx / 4")}; let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; - let x_value = ${v===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; + let x_value = ${b===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${$.getByOffset("global_idx")};`}; // Set scale input - ${w?`let scale_value= ${x.getByOffset("0")}`:_?` + ${w?`let scale_value= ${T.getByOffset("0")}`:f?` let scale_index = ${M.indicesGet("output_indices","uniforms.axis")}; - let scale_value= ${x.getByOffset("scale_index")};`:` - var scale_indices: ${x.type.indices} = output_indices; - let index = ${x.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; - ${x.indicesSet("scale_indices","uniforms.axis","index")}; - let scale_value= ${x.getByIndices("scale_indices")};`}; + let scale_value= ${T.getByOffset("scale_index")};`:` + var scale_indices: ${T.type.indices} = output_indices; + let index = ${T.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${T.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${T.getByIndices("scale_indices")};`}; // Set zero-point input ${g?w?l?` let zero_point_input = ${g.getByOffset("0")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${g.getByOffset("0")}`:_?l?` + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${g.getByOffset("0")}`:f?l?` let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${g.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${g.getByOffset("zero_point_index")};`:l?` - let zero_point_offset = ${x.indicesToOffset("scale_indices")}; + let zero_point_offset = ${T.indicesToOffset("scale_indices")}; let zero_point_input = ${g.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${g.getByIndices("scale_indices")};`:`let zero_point_value = ${l?i?"i32":"u32":S.type.value}(0);`}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${g.getByIndices("scale_indices")};`:`let zero_point_value = ${l?i?"i32":"u32":$.type.value}(0);`}; // Compute and write output ${M.setByOffset("global_idx",`${M.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:Math.ceil(a/v/64),y:1,z:1},programUniforms:B})}},yg=(e,r)=>{gg(e.inputs,r),e.compute(wg(e.inputs,r))},Mg=e=>Dt({axis:e.axis,blockSize:e.blockSize})}),bg,vg,xg,Pv=je(()=>{ss(),pt(),vt(),bg=(e,r,t)=>{let s=e===r,i=er&&t>0;if(s||i||n)throw new Error("Range these inputs' contents are invalid.")},vg=(e,r,t,s)=>{let i=Math.abs(Math.ceil((r-e)/t)),n=[i],o=i,a=[{type:12,data:o},{type:s,data:e},{type:s,data:t},...nt(n)],l=d=>{let p=tt("output",s,n.length),u=p.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getShaderSource:N,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:Math.ceil(a/b/64),y:1,z:1},programUniforms:B})}},Mg=(e,r)=>{wg(e.inputs,r),e.compute(yg(e.inputs,r))},bg=e=>Dt({axis:e.axis,blockSize:e.blockSize})}),vg,xg,Tg,zv=Ue(()=>{ss(),pt(),xt(),vg=(e,r,t)=>{let s=e===r,i=er&&t>0;if(s||i||n)throw new Error("Range these inputs' contents are invalid.")},xg=(e,r,t,s)=>{let i=Math.abs(Math.ceil((r-e)/t)),n=[i],o=i,a=[{type:12,data:o},{type:s,data:e},{type:s,data:t},...nt(n)],l=d=>{let p=tt("output",s,n.length),u=p.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` ${d.registerUniforms(h).declareVariables(p)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:a})}},xg=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Vt.webgpu.validateInputContent&&bg(r,t,s),e.compute(vg(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Tg,Eg,Pg,Cg,Cv=je(()=>{pt(),yt(),Yt(),vt(),Tg=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let i=`{ + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:a})}},Tg=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Vt.webgpu.validateInputContent&&vg(r,t,s),e.compute(xg(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Eg,Pg,Cg,Sg,Bv=Ue(()=>{pt(),Mt(),Yt(),xt(),Eg=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let i=`{ var oldValue = 0; loop { let newValueF32 =`,n=`; @@ -2234,8 +2234,8 @@ fn calculateOutputIndex(index: u32) -> u32 { } }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` ${i}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` - ${i}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${i}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${i}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Eg=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t,n=1,o=Math.ceil(xe.size(s)/n),a=s[s.length-1],l=xe.sizeFromDimension(t,a),d=[{type:12,data:o},{type:12,data:a},{type:12,data:l},...nt(e[1].dims,e[2].dims,i)],p=u=>{let h=$e("indices",e[1].dataType,e[1].dims.length),w=$e("updates",e[2].dataType,e[2].dims.length,n),_=r.reduction!=="none"&&r.reduction!==""?Lp("output",e[0].dataType,i.length):tt("output",e[0].dataType,i.length,n);return` - ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(h,w,_)} + ${i}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${i}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${i}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Pg=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t,n=1,o=Math.ceil(xe.size(s)/n),a=s[s.length-1],l=xe.sizeFromDimension(t,a),d=[{type:12,data:o},{type:12,data:a},{type:12,data:l},...nt(e[1].dims,e[2].dims,i)],p=u=>{let h=$e("indices",e[1].dataType,e[1].dims.length),w=$e("updates",e[2].dataType,e[2].dims.length,n),f=r.reduction!=="none"&&r.reduction!==""?zp("output",e[0].dataType,i.length):tt("output",e[0].dataType,i.length,n);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(h,w,f)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var hasDuplicates = false; @@ -2288,11 +2288,11 @@ fn calculateOutputIndex(index: u32) -> u32 { for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; - ${Tg(r.reduction,"output[data_offset + i]","value",_.type.value)} + ${Eg(r.reduction,"output[data_offset + i]","value",f.type.value)} } - }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d}),getShaderSource:p}},Pg=e=>Dt({reduction:e.reduction}),Cg=(e,r)=>{e.compute(Eg(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Sg,$g,kg,$c,Ig,Ag,Fg,Og,Dg,Lg,zg,Bg,kc,Rg,Ng,jg,Ug,Vg,Wg,Gg,Sv=je(()=>{pt(),yt(),Yt(),vt(),Sg=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and - one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},$g=(e,r,t)=>{r.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((i,n)=>s[i]=e[n]),s},kg=(e,r,t,s,i,n)=>{let[o,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],d=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==d&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Sg(s,r),r.axes.length>0&&$g(s,r.axes,d).forEach((p,u)=>s[u]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>i.push(Number(p))),i.length!==0&&i.length!==d&&t>=18&&i.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof i<"u"&&s.length>0&&i.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},$c=(e,r,t,s)=>` + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d}),getShaderSource:p}},Cg=e=>Dt({reduction:e.reduction}),Sg=(e,r)=>{e.compute(Pg(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),$g,kg,Ig,kc,Ag,Fg,Og,Dg,Lg,zg,Bg,Rg,Ic,Ng,jg,Ug,Vg,Wg,Gg,Kg,Rv=Ue(()=>{pt(),Mt(),Yt(),xt(),$g=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},kg=(e,r,t)=>{r.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((i,n)=>s[i]=e[n]),s},Ig=(e,r,t,s,i,n)=>{let[o,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],d=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==d&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");$g(s,r),r.axes.length>0&&kg(s,r.axes,d).forEach((p,u)=>s[u]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>i.push(Number(p))),i.length!==0&&i.length!==d&&t>=18&&i.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof i<"u"&&s.length>0&&i.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},kc=(e,r,t,s)=>` // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). @@ -2300,12 +2300,12 @@ fn calculateOutputIndex(index: u32) -> u32 { let whole = ${s}(big / (${t})); let fract = ${s}(big % (${t})) / ${s}(${t}); return whole + fract; -`,Ig=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, +`,Ag=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` if (xScale < 1.0 || floor(xScale) != xScale) { return ${r}(xResized) / ${r}(xScale); } else { - ${$c("xResized","lengthOriginal","lengthResized",r)} + ${kc("xResized","lengthOriginal","lengthResized",r)} } `;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; @@ -2314,7 +2314,7 @@ fn calculateOutputIndex(index: u32) -> u32 { }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { - ${$c("xResized","lengthOriginal - 1","lengthResized - 1",r)} + ${kc("xResized","lengthOriginal - 1","lengthResized - 1",r)} }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${r}(roiStart) * ${r}(lengthOriginal - 1) + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / @@ -2325,7 +2325,7 @@ fn calculateOutputIndex(index: u32) -> u32 { const adjustment = ${r}(lengthResized) / outputWidth; const center = ${r}(lengthOriginal) / 2; const offset = center * (1 - adjustment); - return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Ag=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Fg=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),i=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,o)=>{s[n]=i[o],s[o+t]=i[r.length+o]}),s):i},Og=(e,r,t,s)=>{let i=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>i.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,o)=>i[n]=t[o])}else t.forEach(n=>i.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((n,o)=>Math.round(n*r[o]))}return i},Dg=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let i=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>i[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),i.forEach((n,o)=>i[o]=Math.round(n*r[o]))),i},Lg=(e,r,t,s,i)=>` + return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Fg=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Og=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),i=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,o)=>{s[n]=i[o],s[o+t]=i[r.length+o]}),s):i},Dg=(e,r,t,s)=>{let i=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>i.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,o)=>i[n]=t[o])}else t.forEach(n=>i.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((n,o)=>Math.round(n*r[o]))}return i},Lg=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let i=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>i[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),i.forEach((n,o)=>i[o]=Math.round(n*r[o]))),i},zg=(e,r,t,s,i)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { var original_indices: array<${e.type.value}, ${t.length}>; for (var i:u32 = 0; i < ${t.length}; i++) { @@ -2343,7 +2343,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return original_indices; - }`,zg=(e,r,t,s,i,n,o)=>` + }`,Bg=(e,r,t,s,i,n,o)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${s.length}; i++) { @@ -2374,7 +2374,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")} } return input_indices; - }`,Bg=(e,r)=>` + }`,Rg=(e,r)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${r.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; @@ -2383,15 +2383,15 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return true; - }`,kc=(e,r,t,s)=>e.rank>s?` + }`,Ic=(e,r,t,s)=>e.rank>s?` ${e.indicesSet("input_indices",r,"channel")}; ${e.indicesSet("input_indices",t,"batch")}; -`:"",Rg=(e,r,t,s,i)=>{let[n,o,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return` +`:"",Ng=(e,r,t,s,i)=>{let[n,o,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(row, ${t[o]} - 1))`)}; ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; - ${kc(e,l,n,2)} + ${Ic(e,l,n,2)} return ${e.getByIndices("input_indices")}; } @@ -2427,7 +2427,7 @@ fn calculateOutputIndex(index: u32) -> u32 { dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); - }`},Ng=(e,r,t,s,i,n,o,a,l,d)=>{let p=t.length===2,[u,h]=p?[0,1]:[2,3],w=e.type.value,_=P=>{let A=P===u?"row":"col";return` + }`},jg=(e,r,t,s,i,n,o,a,l,d)=>{let p=t.length===2,[u,h]=p?[0,1]:[2,3],w=e.type.value,f=P=>{let A=P===u?"row":"col";return` fn ${A}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${w} { var output_index = ${r.indicesGet("output_indices",P)}; var originalIdx: ${w} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[P]}, @@ -2451,8 +2451,8 @@ fn calculateOutputIndex(index: u32) -> u32 { } return cubicInterpolation1D(data, coefs); }`};return` - ${_(u)}; - ${_(h)}; + ${f(u)}; + ${f(h)}; fn getCubicInterpolationCoefs(s: ${w}) -> array<${w}, 4> { var absS = abs(s); var coeffs: array<${w}, 4> = array<${w}, 4>(0.0, 0.0, 0.0, 0.0); @@ -2475,13 +2475,13 @@ fn calculateOutputIndex(index: u32) -> u32 { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } - `},jg=(e,r,t,s,i)=>{let[n,o,a,l,d]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + `},Ug=(e,r,t,s,i)=>{let[n,o,a,l,d]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",o,`max(0, min(depth, ${t[o]} - 1))`)}; ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; - ${kc(e,d,n,3)} + ${Ic(e,d,n,3)} return ${e.getByIndices("input_indices")}; } @@ -2534,18 +2534,18 @@ fn calculateOutputIndex(index: u32) -> u32 { } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); - }`},Ug=(e,r,t,s,i,n)=>{let o=e.dims,a=Fg(n,r.axes,o.length),l=Og(o,s,i,r.axes),d=s.slice();s.length===0&&(d=o.map((y,S)=>y===0?1:l[S]/y),r.keepAspectRatioPolicy!=="stretch"&&(l=Dg(o,d,r)));let p=tt("output",e.dataType,l.length),u=$e("input",e.dataType,o.length),h=xe.size(l),w=o.length===l.length&&o.every((y,S)=>y===l[S]),_=r.coordinateTransformMode==="tf_crop_and_resize",P=r.extrapolationValue,A=u.type.value,v=y=>` + }`},Vg=(e,r,t,s,i,n)=>{let o=e.dims,a=Og(n,r.axes,o.length),l=Dg(o,s,i,r.axes),d=s.slice();s.length===0&&(d=o.map((y,$)=>y===0?1:l[$]/y),r.keepAspectRatioPolicy!=="stretch"&&(l=Lg(o,d,r)));let p=tt("output",e.dataType,l.length),u=$e("input",e.dataType,o.length),h=xe.size(l),w=o.length===l.length&&o.every((y,$)=>y===l[$]),f=r.coordinateTransformMode==="tf_crop_and_resize",P=r.extrapolationValue,A=u.type.value,b=y=>` ${w?"":` - ${Ig(r.coordinateTransformMode,A)}; + ${Ag(r.coordinateTransformMode,A)}; ${(()=>{switch(r.mode){case"nearest":return` - ${Bg(u,o)}; - ${Ag(r.nearestMode,t,A)}; - ${zg(u,p,o,l,d.length,a.length,_)}; + ${Rg(u,o)}; + ${Fg(r.nearestMode,t,A)}; + ${Bg(u,p,o,l,d.length,a.length,f)}; `;case"linear":return` - ${Lg(p,o,l,d.length,a.length)}; - ${(()=>{if(o.length===2||o.length===4)return`${Rg(u,p,o,_,P)}`;if(o.length===3||o.length===5)return`${jg(u,p,o,_,P)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + ${zg(p,o,l,d.length,a.length)}; + ${(()=>{if(o.length===2||o.length===4)return`${Ng(u,p,o,f,P)}`;if(o.length===3||o.length===5)return`${Ug(u,p,o,f,P)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` - ${(()=>{if(o.length===2||o.length===4)return`${Ng(u,p,o,l,d,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + ${(()=>{if(o.length===2||o.length===4)return`${jg(u,p,o,l,d,a,r.cubicCoeffA,f,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${y.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",a.length).declareVariables(u,p)} @@ -2561,11 +2561,11 @@ fn calculateOutputIndex(index: u32) -> u32 { output[global_idx] = ${r.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${o.length===2||o.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; `} - }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${d.length>0?r.mode==="cubic"?d:d.length:""}|${i.length>0?i:""}|${a.length>0?a:""}|${w}|${r.mode==="nearest"?o.length:o}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:d},{type:1,data:a},...nt(o,l)]})}},Vg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Wg=(e,r)=>{let t=[],s=[],i=[],n=Vg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");kg(e.inputs,r,n,t,s,i),e.compute(Ug(e.inputs[0],r,n,t,s,i),{inputs:[0]})},Gg=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,i=e.cubicCoeffA,n=e.excludeOutside!==0,o=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,d=e.nearestMode===""?"simple":e.nearestMode;return Dt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:i,excludeOutside:n,extrapolationValue:o,keepAspectRatioPolicy:a,mode:l,nearestMode:d})}}),Kg,Hg,qg,$v=je(()=>{pt(),yt(),Yt(),vt(),Kg=(e,r)=>{let[t,s,i,n]=e,{numHeads:o,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!xe.areEqual(s.dims,[])&&!xe.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!xe.areEqual(i.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],d=t.dims[t.dims.length-2],p=i.dims[0],u=xe.sizeFromDimension(t.dims,1)/d,h=a===0?i.dims[1]*2:u/o;if(a>h)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(d!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(h/2!==i.dims[1]&&a/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(d>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Hg=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:i,scale:n}=r,o=e[0].dims[0],a=xe.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],d=a/l,p=e[2].dims[1],u=i===0?p*2:d/s,h=new Array(o,l,d/u,u-p),w=xe.computeStrides(h),_=[{type:1,data:n},{type:12,data:h},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[a,d,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,u,l*u,1]}):[],...nt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],P=A=>{let v=$e("input",e[0].dataType,e[0].dims.length),y=$e("position_ids",e[1].dataType,e[1].dims.length),S=$e("cos_cache",e[2].dataType,e[2].dims.length),x=$e("sin_cache",e[3].dataType,e[3].dims.length),g=tt("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:w.length},{name:"input_output_strides",type:"u32",length:w.length}]),` - ${A.declareVariables(v,y,S,x,g)} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${d.length>0?r.mode==="cubic"?d:d.length:""}|${i.length>0?i:""}|${a.length>0?a:""}|${w}|${r.mode==="nearest"?o.length:o}`,inputDependencies:["rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:d},{type:1,data:a},...nt(o,l)]})}},Wg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Gg=(e,r)=>{let t=[],s=[],i=[],n=Wg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ig(e.inputs,r,n,t,s,i),e.compute(Vg(e.inputs[0],r,n,t,s,i),{inputs:[0]})},Kg=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,i=e.cubicCoeffA,n=e.excludeOutside!==0,o=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,d=e.nearestMode===""?"simple":e.nearestMode;return Dt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:i,excludeOutside:n,extrapolationValue:o,keepAspectRatioPolicy:a,mode:l,nearestMode:d})}}),Hg,qg,Qg,Nv=Ue(()=>{pt(),Mt(),Yt(),xt(),Hg=(e,r)=>{let[t,s,i,n]=e,{numHeads:o,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!xe.areEqual(s.dims,[])&&!xe.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!xe.areEqual(i.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],d=t.dims[t.dims.length-2],p=i.dims[0],u=xe.sizeFromDimension(t.dims,1)/d,h=a===0?i.dims[1]*2:u/o;if(a>h)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(d!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(h/2!==i.dims[1]&&a/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(d>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},qg=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:i,scale:n}=r,o=e[0].dims[0],a=xe.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],d=a/l,p=e[2].dims[1],u=i===0?p*2:d/s,h=new Array(o,l,d/u,u-p),w=xe.computeStrides(h),f=[{type:1,data:n},{type:12,data:h},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[a,d,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,u,l*u,1]}):[],...nt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],P=A=>{let b=$e("input",e[0].dataType,e[0].dims.length),y=$e("position_ids",e[1].dataType,e[1].dims.length),$=$e("cos_cache",e[2].dataType,e[2].dims.length),T=$e("sin_cache",e[3].dataType,e[3].dims.length),g=tt("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:w.length},{name:"input_output_strides",type:"u32",length:w.length}]),` + ${A.declareVariables(b,y,$,T,g)} ${A.mainStart(jn)} - let half_rotary_emb_dim = uniforms.${S.name}_shape[1]; + let half_rotary_emb_dim = uniforms.${$.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")} @@ -2577,17 +2577,17 @@ fn calculateOutputIndex(index: u32) -> u32 { u32(${y.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); let j = i + select(half_rotary_emb_dim, 1, ${t}); - let re = ${v.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - - ${v.getByOffset("j")} * ${x.get("position_id","bsnh[3]")}; + let re = ${b.getByOffset("i")} * ${$.get("position_id","bsnh[3]")} - + ${b.getByOffset("j")} * ${T.get("position_id","bsnh[3]")}; ${g.setByOffset("i","re")} - let im = ${v.getByOffset("i")} * ${x.get("position_id","bsnh[3]")} + - ${v.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; + let im = ${b.getByOffset("i")} * ${T.get("position_id","bsnh[3]")} + + ${b.getByOffset("j")} * ${$.get("position_id","bsnh[3]")}; ${g.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; - ${g.setByOffset("k",v.getByOffset("k"))} + ${g.setByOffset("k",b.getByOffset("k"))} } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:Dt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(xe.size(h)/jn)},programUniforms:_})}},qg=(e,r)=>{Kg(e.inputs,r),e.compute(Hg(e.inputs,r))}}),Qg,Xg,Jg,kv=je(()=>{pt(),yt(),vt(),Qg=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Xg=(e,r,t,s)=>{let i=r.simplified,n=e[0].dims,o=xe.size(n),a=n,l=o,d=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],u=!i&&e.length>3,h=e.length>4,w=s&&t>1,_=s&&t>2,P=t>3,A=64,v=Xt(d),y=[{type:12,data:l},{type:12,data:v},{type:12,data:d},{type:1,data:r.epsilon}],S=g=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],E=[$e("x",e[0].dataType,e[0].dims,v),$e("skip",e[1].dataType,e[1].dims,v),$e("gamma",e[2].dataType,e[2].dims,v)];u&&E.push($e("beta",e[3].dataType,e[3].dims,v)),h&&E.push($e("bias",e[4].dataType,e[4].dims,v)),E.push(tt("output",e[0].dataType,a,v)),w&&E.push(tt("mean_output",1,p)),_&&E.push(tt("inv_std_output",1,p)),P&&E.push(tt("input_skip_bias_sum",e[0].dataType,a,v));let k=lr(e[0].dataType),B=lr(1,v);return` + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Dt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(xe.size(h)/jn)},programUniforms:f})}},Qg=(e,r)=>{Hg(e.inputs,r),e.compute(qg(e.inputs,r))}}),Xg,Jg,Yg,jv=Ue(()=>{pt(),Mt(),xt(),Xg=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Jg=(e,r,t,s)=>{let i=r.simplified,n=e[0].dims,o=xe.size(n),a=n,l=o,d=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],u=!i&&e.length>3,h=e.length>4,w=s&&t>1,f=s&&t>2,P=t>3,A=64,b=Xt(d),y=[{type:12,data:l},{type:12,data:b},{type:12,data:d},{type:1,data:r.epsilon}],$=g=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],E=[$e("x",e[0].dataType,e[0].dims,b),$e("skip",e[1].dataType,e[1].dims,b),$e("gamma",e[2].dataType,e[2].dims,b)];u&&E.push($e("beta",e[3].dataType,e[3].dims,b)),h&&E.push($e("bias",e[4].dataType,e[4].dims,b)),E.push(tt("output",e[0].dataType,a,b)),w&&E.push(tt("mean_output",1,p)),f&&E.push(tt("inv_std_output",1,p)),P&&E.push(tt("input_skip_bias_sum",e[0].dataType,a,b));let k=lr(e[0].dataType),B=lr(1,b);return` ${g.registerUniforms(M).declareVariables(...E)} var sum_shared : array<${B}, ${A}>; @@ -2611,7 +2611,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let value = input_value + skip_value + bias_value; ${P?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; - let f32_value = ${Un(k,v,"value")}; + let f32_value = ${Un(k,b,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } @@ -2629,17 +2629,17 @@ fn calculateOutputIndex(index: u32) -> u32 { let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; - let mean = ${Ws("sum",v)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Ws("square_sum",v)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + let mean = ${Ws("sum",b)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Ws("square_sum",b)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); ${w?"mean_output[global_idx] = mean;":""} - ${_?"inv_std_output[global_idx] = inv_std_dev;":""} + ${f?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${i?"":`- ${k}(mean)`}) * ${k}(inv_std_dev) * gamma[offset1d + i] ${u?"+ beta[offset1d + i]":""}; } - }`},x=[{dims:a,dataType:e[0].dataType}];return t>1&&x.push({dims:p,dataType:1}),t>2&&x.push({dims:p,dataType:1}),t>3&&x.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${v};${w};${_};${P}`,inputDependencies:e.map((g,M)=>"type")},getShaderSource:S,getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(l/d)},programUniforms:y})}},Jg=(e,r)=>{Qg(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(Xg(e.inputs,r,e.outputCount,!1),{outputs:t})}}),Yg,Ni,Zg,Ic,ew,tw,rw,sw,Iv=je(()=>{pt(),yt(),Yt(),vt(),Yg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Ni=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},Zg=(e,r)=>{if(e.length>1){let t=Ni(e,1),s=Ni(e,2),i=Ni(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Dt({starts:t,ends:s,axes:i})}else return r},Ic=(e,r,t,s,i)=>{let n=e;return e<0&&(n+=t[s[r]]),i[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},ew=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + }`},T=[{dims:a,dataType:e[0].dataType}];return t>1&&T.push({dims:p,dataType:1}),t>2&&T.push({dims:p,dataType:1}),t>3&&T.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${b};${w};${f};${P}`,inputDependencies:e.map((g,M)=>"type")},getShaderSource:$,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(l/d)},programUniforms:y})}},Yg=(e,r)=>{Xg(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(Jg(e.inputs,r,e.outputCount,!1),{outputs:t})}}),Zg,Ni,ew,Ac,tw,rw,sw,nw,Uv=Ue(()=>{pt(),Mt(),Yt(),xt(),Zg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Ni=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},ew=(e,r)=>{if(e.length>1){let t=Ni(e,1),s=Ni(e,2),i=Ni(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Dt({starts:t,ends:s,axes:i})}else return r},Ac=(e,r,t,s,i)=>{let n=e;return e<0&&(n+=t[s[r]]),i[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},tw=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${t.length}; i >= 0; i--) { @@ -2657,29 +2657,29 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; - }`,tw=(e,r)=>{let t=e[0].dims,s=xe.size(t),i=r.axes.length>0?xe.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=Ni(e,4);n.forEach(v=>v!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(i.length).fill(1));let o=r.starts.map((v,y)=>Ic(v,y,t,i,n)),a=r.ends.map((v,y)=>Ic(v,y,t,i,n));if(i.length!==o.length||i.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==t.length)for(let v=0;vMath.sign(v));n.forEach((v,y,S)=>{if(v<0){let x=(a[y]-o[y])/v,g=o[y],M=g+x*n[y];o[y]=M,a[y]=g,S[y]=-v}});let d=t.slice(0);i.forEach((v,y)=>{d[v]=Math.ceil((a[v]-o[v])/n[v])});let p={dims:d,dataType:e[0].dataType},u=tt("output",e[0].dataType,d.length),h=$e("input",e[0].dataType,e[0].dims.length),w=xe.size(d),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],P=[{type:12,data:w},{type:12,data:o},{type:6,data:l},{type:12,data:n},...nt(e[0].dims,d)],A=v=>` - ${v.registerUniforms(_).declareVariables(h,u)} - ${ew(h,u,t)} - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + }`,rw=(e,r)=>{let t=e[0].dims,s=xe.size(t),i=r.axes.length>0?xe.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=Ni(e,4);n.forEach(b=>b!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(i.length).fill(1));let o=r.starts.map((b,y)=>Ac(b,y,t,i,n)),a=r.ends.map((b,y)=>Ac(b,y,t,i,n));if(i.length!==o.length||i.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==t.length)for(let b=0;bMath.sign(b));n.forEach((b,y,$)=>{if(b<0){let T=(a[y]-o[y])/b,g=o[y],M=g+T*n[y];o[y]=M,a[y]=g,$[y]=-b}});let d=t.slice(0);i.forEach((b,y)=>{d[b]=Math.ceil((a[b]-o[b])/n[b])});let p={dims:d,dataType:e[0].dataType},u=tt("output",e[0].dataType,d.length),h=$e("input",e[0].dataType,e[0].dims.length),w=xe.size(d),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],P=[{type:12,data:w},{type:12,data:o},{type:6,data:l},{type:12,data:n},...nt(e[0].dims,d)],A=b=>` + ${b.registerUniforms(f).declareVariables(h,u)} + ${tw(h,u,t)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${u.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${u.setByOffset("global_idx",h.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${o.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:P})}},rw=(e,r)=>{Yg(e.inputs,r);let t=Zg(e.inputs,r);e.compute(tw(e.inputs,t),{inputs:[0]})},sw=e=>{let r=e.starts,t=e.ends,s=e.axes;return Dt({starts:r,ends:t,axes:s})}}),nw,iw,ow,aw,Av=je(()=>{pt(),yt(),Yt(),Gs(),vt(),nw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},iw=(e,r)=>{let t=e.inputs[0],s=t.dims,i=xe.size(s),n=s.length,o=xe.normalizeAxis(r.axis,n),a=ok),d[o]=n-1,d[n-1]=o,l=e.compute(Nr(t,d),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,u=p[n-1],h=i/u,w=Xt(u),_=u/w,P=64;h===1&&(P=256);let A=(E,k)=>k===4?`max(max(${E}.x, ${E}.y), max(${E}.z, ${E}.w))`:k===2?`max(${E}.x, ${E}.y)`:k===3?`max(max(${E}.x, ${E}.y), ${E}.z)`:E,v=$e("x",l.dataType,l.dims,w),y=tt("result",l.dataType,l.dims,w),S=v.type.value,x=lr(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,g=E=>` - var rowMaxShared : ${S}; - var rowSumShared : ${S}; - var threadShared : array<${S}, ${P}>; + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${o.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:P})}},sw=(e,r)=>{Zg(e.inputs,r);let t=ew(e.inputs,r);e.compute(rw(e.inputs,t),{inputs:[0]})},nw=e=>{let r=e.starts,t=e.ends,s=e.axes;return Dt({starts:r,ends:t,axes:s})}}),iw,ow,aw,lw,Vv=Ue(()=>{pt(),Mt(),Yt(),Gs(),xt(),iw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ow=(e,r)=>{let t=e.inputs[0],s=t.dims,i=xe.size(s),n=s.length,o=xe.normalizeAxis(r.axis,n),a=ok),d[o]=n-1,d[n-1]=o,l=e.compute(Nr(t,d),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,u=p[n-1],h=i/u,w=Xt(u),f=u/w,P=64;h===1&&(P=256);let A=(E,k)=>k===4?`max(max(${E}.x, ${E}.y), max(${E}.z, ${E}.w))`:k===2?`max(${E}.x, ${E}.y)`:k===3?`max(max(${E}.x, ${E}.y), ${E}.z)`:E,b=$e("x",l.dataType,l.dims,w),y=tt("result",l.dataType,l.dims,w),$=b.type.value,T=lr(l.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,g=E=>` + var rowMaxShared : ${$}; + var rowSumShared : ${$}; + var threadShared : array<${$}, ${P}>; - fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} { + fn getValue(row: i32, col: i32, row_stride: i32) -> ${$} { let index = row * row_stride + col; return x[index]; } - fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) { + fn setValue(row: i32, col: i32, row_stride: i32, value: ${$}) { let index = row * row_stride + col; result[index] = value; } - ${E.registerUniform("packedCols","i32").declareVariables(v,y)} + ${E.registerUniform("packedCols","i32").declareVariables(b,y)} ${E.mainStart(P)} let gindex = i32(global_idx); let lindex = i32(local_idx); @@ -2689,7 +2689,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let row_stride : i32 = uniforms.packedCols; // find the rows max - ${x} + ${T} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); @@ -2708,12 +2708,12 @@ fn calculateOutputIndex(index: u32) -> u32 { workgroupBarrier(); } if (lindex == 0) { - rowMaxShared = ${S}(${A("threadShared[0]",w)}); + rowMaxShared = ${$}(${A("threadShared[0]",w)}); } workgroupBarrier(); // find the rows sum - var threadSum = ${S}(0.0); + var threadSum = ${$}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; @@ -2728,7 +2728,7 @@ fn calculateOutputIndex(index: u32) -> u32 { workgroupBarrier(); } if (lindex == 0) { - rowSumShared = ${S}(${Ws("threadShared[0]",w)}); + rowSumShared = ${$}(${Ws("threadShared[0]",w)}); } workgroupBarrier(); @@ -2737,7 +2737,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } - }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${w};${P}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:_}]}),getShaderSource:g},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Nr(M,d),{inputs:[M]})},ow=(e,r)=>{nw(e.inputs),iw(e,r)},aw=e=>Dt({axis:e.axis})}),Ac,lw,dw,cw,uw,Fv=je(()=>{pt(),yt(),vt(),Ac=e=>Array.from(e.getBigInt64Array(),Number),lw=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ac(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},dw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Ac(e[1]),i=dw(t,s),n=xe.size(i),o=e[0].dataType,a=$e("input",o,t.length),l=tt("output",o,i.length),d=p=>` + }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${w};${P}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:f}]}),getShaderSource:g},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Nr(M,d),{inputs:[M]})},aw=(e,r)=>{iw(e.inputs),ow(e,r)},lw=e=>Dt({axis:e.axis})}),Fc,dw,cw,uw,pw,Wv=Ue(()=>{pt(),Mt(),xt(),Fc=e=>Array.from(e.getBigInt64Array(),Number),dw=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Fc(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},cw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Fc(e[1]),i=cw(t,s),n=xe.size(i),o=e[0].dataType,a=$e("input",o,t.length),l=tt("output",o,i.length),d=p=>` const inputShape = ${a.indices(...t)}; ${p.registerUniform("output_size","u32").declareVariables(a,l)} ${p.mainStart()} @@ -2751,7 +2751,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${a.indicesSet("input_indices","i","input_dim_value")} } ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...nt(e[0].dims,i)]}),getShaderSource:d}},uw=e=>{lw(e.inputs),e.compute(cw(e.inputs),{inputs:[0]})}}),pw,hw,mw,Ov=je(()=>{pt(),yt(),vt(),pw=(e,r,t,s,i)=>{let n=tt("output_data",i,t.length,4),o=$e("a_data",r[1].dataType,r[1].dims.length,4),a=$e("b_data",r[2].dataType,r[2].dims.length,4),l=$e("c_data",r[0].dataType,r[0].dims.length,4),d,p=(u,h,w)=>`select(${h}, ${u}, ${w})`;if(!s)d=n.setByOffset("global_idx",p(o.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(h,w,_="")=>{let P=`a_data[index_a${w}][component_a${w}]`,A=`b_data[index_b${w}][component_b${w}]`,v=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return` + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...nt(e[0].dims,i)]}),getShaderSource:d}},pw=e=>{dw(e.inputs),e.compute(uw(e.inputs),{inputs:[0]})}}),hw,mw,_w,Gv=Ue(()=>{pt(),Mt(),xt(),hw=(e,r,t,s,i)=>{let n=tt("output_data",i,t.length,4),o=$e("a_data",r[1].dataType,r[1].dims.length,4),a=$e("b_data",r[2].dataType,r[2].dims.length,4),l=$e("c_data",r[0].dataType,r[0].dims.length,4),d,p=(u,h,w)=>`select(${h}, ${u}, ${w})`;if(!s)d=n.setByOffset("global_idx",p(o.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(h,w,f="")=>{let P=`a_data[index_a${w}][component_a${w}]`,A=`b_data[index_b${w}][component_b${w}]`,b=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return` let output_indices${w} = ${n.offsetToIndices(`global_idx * 4u + ${w}u`)}; let offset_a${w} = ${o.broadcastedIndicesToOffset(`output_indices${w}`,n)}; let offset_b${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,n)}; @@ -2762,7 +2762,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let component_a${w} = offset_a${w} % 4u; let component_b${w} = offset_b${w} % 4u; let component_c${w} = offset_c${w} % 4u; - ${h}[${w}] = ${_}(${p(P,A,v)}); + ${h}[${w}] = ${f}(${p(P,A,b)}); `};i===9?d=` var data = vec4(0); ${u("data",0,"u32")} @@ -2779,10 +2779,10 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${d} - }`},hw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,i=e[1].dataType,n=!(xe.areEqual(r,t)&&xe.areEqual(t,s)),o=r,a=xe.size(r);if(n){let d=Nn.calcShape(Nn.calcShape(r,t,!1),s,!1);if(!d)throw new Error("Can't perform where op on the given tensors");o=d,a=xe.size(o)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>pw(d,e,o,n,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...nt(s,r,t,o)]})}},mw=e=>{e.compute(hw(e.inputs))}}),fw,Dv=je(()=>{qb(),qd(),Qb(),Xb(),Jb(),Yb(),Zb(),nv(),ov(),av(),lv(),dv(),cv(),uv(),pv(),hv(),mv(),fv(),_v(),gv(),wv(),yv(),Mv(),bv(),vv(),S_(),xv(),Tv(),Ev(),Pv(),Cv(),Gd(),Sv(),$v(),kv(),Iv(),Av(),D_(),Fv(),Gs(),Yd(),Ov(),fw=new Map([["Abs",[Qh]],["Acos",[Xh]],["Acosh",[Jh]],["Add",[Bm]],["ArgMax",[Oh,Hd]],["ArgMin",[Fh,Hd]],["Asin",[Yh]],["Asinh",[Zh]],["Atan",[em]],["Atanh",[tm]],["Attention",[Nh]],["AveragePool",[cg,dg]],["BatchNormalization",[Wh]],["BiasAdd",[Hh]],["BiasSplitGelu",[Dm]],["Cast",[sm,rm]],["Ceil",[om]],["Clip",[im]],["Concat",[Ym,Zm]],["Conv",[uc,dc]],["ConvTranspose",[Cf,Tf]],["Cos",[am]],["Cosh",[lm]],["CumSum",[$f,kf]],["DepthToSpace",[Of,Df]],["DequantizeLinear",[yg,Mg]],["Div",[Rm]],["Einsum",[jf,Uf]],["Elu",[dm,Oi]],["Equal",[Nm]],["Erf",[cm]],["Exp",[um]],["Expand",[Kf]],["FastGelu",[qf]],["Floor",[pm]],["FusedConv",[uc,dc]],["Gather",[Yf,Jf]],["GatherElements",[d_,l_]],["GatherBlockQuantized",[n_,i_]],["GatherND",[e_,t_]],["Gelu",[hm]],["Gemm",[h_,p_]],["GlobalAveragePool",[pg,ug]],["GlobalMaxPool",[_g,fg]],["Greater",[Wm]],["GreaterOrEqual",[Km]],["GridSample",[v_,x_]],["GroupQueryAttention",[B_]],["HardSigmoid",[bm,Mm]],["InstanceNormalization",[j_]],["LayerNormalization",[W_]],["LeakyRelu",[mm,Oi]],["Less",[Gm]],["LessOrEqual",[Hm]],["Log",[$m]],["MatMul",[K_]],["MatMulNBits",[X_,J_]],["MaxPool",[hg,mg]],["Mul",[jm]],["MultiHeadAttention",[C_,E_]],["Neg",[_m]],["Not",[fm]],["Pad",[og]],["Pow",[Um]],["QuickGelu",[Am,Oi]],["Range",[xg]],["Reciprocal",[gm]],["ReduceMin",[Sh]],["ReduceMean",[xh]],["ReduceMax",[Ch]],["ReduceSum",[kh]],["ReduceProd",[$h]],["ReduceL1",[Th]],["ReduceL2",[Eh]],["ReduceLogSum",[Ah]],["ReduceLogSumExp",[Ph]],["ReduceSumSquare",[Ih]],["Relu",[wm]],["Resize",[Wg,Gg]],["RotaryEmbedding",[qg]],["ScatterND",[Cg,Pg]],["Sigmoid",[ym]],["Sin",[vm]],["Sinh",[xm]],["Slice",[rw,sw]],["SkipLayerNormalization",[Jg]],["Split",[F_,O_]],["Sqrt",[Tm]],["Softmax",[ow,aw]],["Sub",[Vm]],["Tan",[Em]],["Tanh",[Pm]],["ThresholdedRelu",[Sm,Oi]],["Tile",[uw]],["Transpose",[Wp,Gp]],["Where",[mw]]])}),_w,Lv=je(()=>{ss(),ks(),vt(),_w=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,i){rs(e.programInfo.name);let n=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let d of r)a.push({binding:a.length,resource:{buffer:d.buffer}});for(let d of t)a.push({binding:a.length,resource:{buffer:d.buffer}});i&&a.push({binding:a.length,resource:i});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}o.setPipeline(e.computePipeline),o.setBindGroup(0,l),o.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Hr(e.programInfo.name)}dispose(){}build(e,r){rs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(d=>{t.features.has(d.feature)&&s.push(`enable ${d.extension};`)});let i=Bp(r,this.backend.device.limits),n=e.getShaderSource(i),o=`${s.join(` + }`},mw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,i=e[1].dataType,n=!(xe.areEqual(r,t)&&xe.areEqual(t,s)),o=r,a=xe.size(r);if(n){let d=Nn.calcShape(Nn.calcShape(r,t,!1),s,!1);if(!d)throw new Error("Can't perform where op on the given tensors");o=d,a=xe.size(o)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>hw(d,e,o,n,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...nt(s,r,t,o)]})}},_w=e=>{e.compute(mw(e.inputs))}}),fw,Kv=Ue(()=>{iv(),Qd(),ov(),av(),lv(),dv(),cv(),_v(),gv(),wv(),yv(),Mv(),bv(),vv(),xv(),Tv(),Ev(),Pv(),Cv(),Sv(),$v(),kv(),Iv(),Av(),Fv(),$f(),Ov(),Dv(),Lv(),zv(),Bv(),Kd(),Rv(),Nv(),jv(),Uv(),Vv(),Lf(),Wv(),Gs(),Zd(),Gv(),fw=new Map([["Abs",[Xh]],["Acos",[Jh]],["Acosh",[Yh]],["Add",[Rm]],["ArgMax",[Dh,qd]],["ArgMin",[Oh,qd]],["Asin",[Zh]],["Asinh",[em]],["Atan",[tm]],["Atanh",[rm]],["Attention",[jh]],["AveragePool",[ug,cg]],["BatchNormalization",[Gh]],["BiasAdd",[qh]],["BiasSplitGelu",[Lm]],["Cast",[nm,sm]],["Ceil",[am]],["Clip",[om]],["Concat",[Zm,e_]],["Conv",[pc,cc]],["ConvTranspose",[C_,T_]],["Cos",[lm]],["Cosh",[dm]],["CumSum",[$_,k_]],["DepthToSpace",[O_,D_]],["DequantizeLinear",[Mg,bg]],["Div",[Nm]],["Einsum",[j_,U_]],["Elu",[cm,Oi]],["Equal",[jm]],["Erf",[um]],["Exp",[pm]],["Expand",[K_]],["FastGelu",[q_]],["Floor",[hm]],["FusedConv",[pc,cc]],["Gather",[Y_,J_]],["GatherElements",[cf,df]],["GatherBlockQuantized",[nf,of]],["GatherND",[ef,tf]],["Gelu",[mm]],["Gemm",[mf,hf]],["GlobalAveragePool",[hg,pg]],["GlobalMaxPool",[gg,fg]],["Greater",[Gm]],["GreaterOrEqual",[Hm]],["GridSample",[xf,Tf]],["GroupQueryAttention",[Rf]],["HardSigmoid",[vm,bm]],["InstanceNormalization",[Uf]],["LayerNormalization",[Gf]],["LeakyRelu",[_m,Oi]],["Less",[Km]],["LessOrEqual",[qm]],["Log",[km]],["MatMul",[Hf]],["MatMulNBits",[Jf,Yf]],["MaxPool",[mg,_g]],["Mul",[Um]],["MultiHeadAttention",[Sf,Pf]],["Neg",[gm]],["Not",[fm]],["Pad",[ag]],["Pow",[Vm]],["QuickGelu",[Fm,Oi]],["Range",[Tg]],["Reciprocal",[wm]],["ReduceMin",[$h]],["ReduceMean",[Th]],["ReduceMax",[Sh]],["ReduceSum",[Ih]],["ReduceProd",[kh]],["ReduceL1",[Eh]],["ReduceL2",[Ph]],["ReduceLogSum",[Fh]],["ReduceLogSumExp",[Ch]],["ReduceSumSquare",[Ah]],["Relu",[ym]],["Resize",[Gg,Kg]],["RotaryEmbedding",[Qg]],["ScatterND",[Sg,Cg]],["Sigmoid",[Mm]],["Sin",[xm]],["Sinh",[Tm]],["Slice",[sw,nw]],["SkipLayerNormalization",[Yg]],["Split",[Of,Df]],["Sqrt",[Em]],["Softmax",[aw,lw]],["Sub",[Wm]],["Tan",[Pm]],["Tanh",[Cm]],["ThresholdedRelu",[$m,Oi]],["Tile",[pw]],["Transpose",[Gp,Kp]],["Where",[_w]]])}),gw,Hv=Ue(()=>{ss(),ks(),xt(),gw=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,i){rs(e.programInfo.name);let n=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let d of r)a.push({binding:a.length,resource:{buffer:d.buffer}});for(let d of t)a.push({binding:a.length,resource:{buffer:d.buffer}});i&&a.push({binding:a.length,resource:i});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}o.setPipeline(e.computePipeline),o.setBindGroup(0,l),o.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Hr(e.programInfo.name)}dispose(){}build(e,r){rs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(d=>{t.features.has(d.feature)&&s.push(`enable ${d.extension};`)});let i=Rp(r,this.backend.device.limits),n=e.getShaderSource(i),o=`${s.join(` `)} ${i.additionalImplementations} -${n}`,a=t.createShaderModule({code:o,label:e.name});St("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Hr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&t<=i&&s<=i)return[r,t,s];let n=r*t*s,o=Math.ceil(Math.sqrt(n));if(o>i){if(o=Math.ceil(Math.cbrt(n)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),gw,ww,yw,Mw,zv=je(()=>{ss(),pt(),ks(),Pp(),Kb(),Dv(),Lv(),gw=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{var i,n;let s=e.name;return(i=e.shaderCache)!=null&&i.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${gw(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},yw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Mw=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=n=>r.features.has(n)&&t.push(n)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new yw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=kp(this),this.programManager=new _w(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Dd(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;rs(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=w);let P=Number(w-this.queryTimeBase),A=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(P)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map(v=>({dims:v.dims,dataType:mn(v.dataType)})),outputsMetadata:h.map(v=>({dims:v.dims,dataType:mn(v.dataType)})),kernelId:o,kernelType:l,kernelName:d,programName:p,startTime:P,endTime:A});else{let v="";u.forEach((S,x)=>{v+=`input[${x}]: [${S.dims}] | ${mn(S.dataType)}, `});let y="";h.forEach((S,x)=>{y+=`output[${x}]: [${S.dims}] | ${mn(S.dataType)}, `}),console.log(`[profiling] kernel "${o}|${l}|${d}|${p}" ${v}${y}execution time: ${A-P} ns`)}ki("GPU",`${p}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),Hr()}run(e,r,t,s,i,n){rs(e.name);let o=[];for(let y=0;yS):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let u=[],h=[];for(let y=0;y=n)throw new Error(`Invalid output index: ${p[y]}`);if(p[y]===-3)continue;let S=p[y]===-1,x=p[y]===-2,g=S||x?i(a[y].dataType,a[y].dims):s(p[y],a[y].dataType,a[y].dims);if(u.push(g),g.data===0)continue;let M=this.gpuDataManager.get(g.data);if(!M)throw new Error(`no GPU data for output: ${g.data}`);if(S&&this.temporaryData.push(M),x){let E=this.kernelPersistentData.get(this.currentKernelId);E||(E=[],this.kernelPersistentData.set(this.currentKernelId,E)),E.push(M)}h.push(M)}if(o.length!==r.length||h.length!==u.length){if(h.length===0)return Hr(e.name),u;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let w;if(d){let y=0,S=[];d.forEach(E=>{let k=typeof E.data=="number"?[E.data]:E.data;if(k.length===0)return;let B=E.type===10?2:4,R,J;E.type===10?(J=k.length>4?16:k.length>2?8:k.length*B,R=k.length>4?16:B*k.length):(J=k.length<=2?k.length*B:16,R=16),y=Math.ceil(y/J)*J,S.push(y);let q=E.type===10?8:4;y+=k.length>4?Math.ceil(k.length/q)*R:k.length*B});let x=16;y=Math.ceil(y/x)*x;let g=new ArrayBuffer(y);d.forEach((E,k)=>{let B=S[k],R=typeof E.data=="number"?[E.data]:E.data;if(E.type===6)new Int32Array(g,B,R.length).set(R);else if(E.type===12)new Uint32Array(g,B,R.length).set(R);else if(E.type===10)new Uint16Array(g,B,R.length).set(R);else if(E.type===1)new Float32Array(g,B,R.length).set(R);else throw new Error(`Unsupported uniform type: ${mn(E.type)}`)});let M=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,g,0,y),this.gpuDataManager.release(M.id),w={offset:0,size:y,buffer:M.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),P=_[1]===1&&_[2]===1,A=ww(e,r,P),v=this.programManager.getArtifact(A);if(v||(v=this.programManager.build(e,_),this.programManager.setArtifact(A,v),St("info",()=>`[artifact] key: ${A}, programName: ${e.name}`)),d&&v.uniformVariablesInfo){if(d.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${d.length} in program "${v.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${A}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:u};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(v,o,h,_,w),Hr(e.name),u}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let i=fw.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let i=s.kernelType,n=s.kernelName,o=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),St("info",()=>`[WebGPU] Start to run kernel "[${i}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),o(r,a[1]),0}catch(d){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${n}" failed. ${d}`)),1}finally{l&&t.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${i}] ${n}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let n=i.get(r),o=this.gpuDataManager.registerExternalBuffer(t,s,n);return i.set(r,[o,t]),o}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await Nd(this,e,r);return Ld(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){St("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){St("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){St("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),bw,Fc,vw,Oc,Dc,Lc,xw,Tw,Bv=je(()=>{ks(),bw=1,Fc=()=>bw++,vw=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Oc=(e,r)=>{let t=vw.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,i)=>s*i)*t/8):0},Dc=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Oc(this.dataType,this.tensorShape)}destroy(){St("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,i)=>s===t[i])}},Lc=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let i=this.tensorManager.getMLContext(e);if(this.wrapper){if(this.wrapper.canReuseTensor(i,r,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Oc(r,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,r,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else St("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},xw=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=Fc();return this.tensorTrackersById.set(e,new Lc(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,i){St("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${i}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,i)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){St("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let i=this.getMLContext(e),n=Fc(),o=new Dc({sessionId:e,context:i,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new Lc(this,o)),this.externalTensors.add(o),n}async getCachedTensor(e,r,t,s,i,n){let o=this.getMLContext(e);for(let[l,d]of this.freeTensors.entries())if(d.canReuseTensor(o,r,t)){St("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let p=this.freeTensors.splice(l,1)[0];return p.sessionId=e,p}St("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let a=await o.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:i,readable:n});return new Dc({sessionId:e,context:o,tensor:a,dataType:r,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Tw=(...e)=>new xw(...e)}),Ia,Ew,Pw,Rv=je(()=>{pt(),hn(),Pp(),Bv(),ks(),Ia=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Ew=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((i,n)=>i===s[n]&&e[i]===r[i])},Pw=class{constructor(e){this.tensorManager=Tw(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Dd(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){St("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){St("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)St("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>Ew(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(i=>i.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){St("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,i){let n=Ia.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,i)}async createTemporaryTensor(e,r,t){St("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Ia.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,r){if(!ar().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");St("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return Ld(t,r)}}registerMLTensor(e,r,t,s){let i=Ia.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,i,s);return St("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,i,n){if(!n)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let a=n.get(o);if(!a)throw new Error(`File with name ${o} not found in preloaded files.`);if(r+t>a.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l=a.slice(r,r+t).buffer,d;switch(i.dataType){case"float32":d=new Float32Array(l);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case"int32":d=new Int32Array(l);break;case"uint32":d=new Uint32Array(l);break;case"int64":d=new BigInt64Array(l);break;case"uint64":d=new BigUint64Array(l);break;case"int8":d=new Int8Array(l);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(l);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return St("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),s.constant(i,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}flush(){}}}),Cw={};Ci(Cw,{init:()=>$w});var Aa,Sw,$w,Nv=je(()=>{pt(),zv(),ks(),yt(),Rv(),Aa=class lb{constructor(r,t,s,i){this.module=r,this.dataType=t,this.data=s,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(xe.size(r)!==xe.size(this.dims))throw new Error("Invalid new shape");return new lb(this.module,this.dataType,this.data,r)}},Sw=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,i=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*i++,n));let o=Number(e.getValue(s*i++,n));this.outputCount=Number(e.getValue(s*i++,n)),this.customDataOffset=Number(e.getValue(s*i++,"*")),this.customDataSize=Number(e.getValue(s*i++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],i=(a,l,d)=>new Aa(this.module,l,this.output(a,d),d),n=(a,l)=>{let d=fn(a,l);if(!d)throw new Error(`Unsupported data type: ${a}`);let p=d>0?this.backend.gpuDataManager.create(d).id:0;return new Aa(this.module,a,p,l)};return this.backend.run(e,t,s,i,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,i=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,i);for(let o=0;o{let i=r.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=new Mw;await n.initialize(t,s),i("webgpu",[n,o=>n.alloc(Number(o)),o=>n.free(o),(o,a,l,d=!1)=>{if(d)St("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(a)}, size=${Number(l)}`),n.memcpy(Number(o),Number(a));else{St("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(a)}, size=${Number(l)}`);let p=r.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(l));n.upload(Number(a),p)}},async(o,a,l)=>{St("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${a}, size=${l}`),await n.download(Number(o),()=>r.HEAPU8.subarray(Number(a)>>>0,Number(a+l)>>>0))},(o,a,l)=>n.createKernel(o,Number(a),l,r.UTF8ToString(r._JsepGetNodeName(Number(a)))),o=>n.releaseKernel(o),(o,a,l,d)=>{St("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${o}, contextDataOffset=${a}`);let p=new Sw(r,n,Number(a));return n.computeKernel(Number(o),p,d)},()=>n.captureBegin(),()=>n.captureEnd(),()=>n.replay()])}else{let n=new Pw(t);i("webnn",[n,()=>n.reserveTensorId(),o=>n.releaseTensorId(o),async(o,a,l,d,p)=>n.ensureTensor(o,a,l,d,p),(o,a)=>{n.uploadTensor(o,a)},async(o,a)=>n.downloadTensor(o,a)])}}}),kw,zc,Bc,Ks,Iw,Fa,Rc,Nc,jc,Uc,Vc,Wc,Aw=je(()=>{Wb(),Gb(),pt(),hn(),$d(),Mp(),kw=(e,r)=>{ar()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},zc=async e=>{kw(e.wasm.numThreads,ya(e.logLevel))},Bc=async(e,r)=>{{let t=(Nv(),ma(Cw)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:n}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",ar(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",ar(),e)}}},Ks=new Map,Iw=e=>{let r=ar(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,i,i+s)!==0&&At("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(i,n)),Number(r.getValue(i+s,n))]}finally{r.stackRestore(t)}},Fa=e=>{let r=ar(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},Rc=async(e,r)=>{var u,h,w;let t,s,i=ar();Array.isArray(e)?[t,s]=e:e.buffer===i.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=Fa(e);let n=0,o=0,a=0,l=[],d=[],p=[];try{if([o,l]=yp(r),(r==null?void 0:r.externalData)&&i.mountExternalData){let g=[];for(let M of r.externalData){let E=typeof M=="string"?M:M.path;g.push(Od(typeof M=="string"?M:M.data).then(k=>{i.mountExternalData(E,k)}))}await Promise.all(g)}for(let g of(r==null?void 0:r.executionProviders)??[])if((typeof g=="string"?g:g.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof g!="string"){let M=g,E=M==null?void 0:M.context,k=M==null?void 0:M.gpuDevice,B=M==null?void 0:M.deviceType,R=M==null?void 0:M.powerPreference;E?i.currentContext=E:k?i.currentContext=await i.jsepCreateMLContext(k):i.currentContext=await i.jsepCreateMLContext({deviceType:B,powerPreference:R})}else i.currentContext=await i.jsepCreateMLContext();break}n=await i._OrtCreateSession(t,s,o),n===0&&At("Can't create a session."),(u=i.jsepOnCreateSession)==null||u.call(i),i.currentContext&&(i.jsepRegisterMLContext(n,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[_,P]=Iw(n),A=!!(r!=null&&r.enableGraphCapture),v=[],y=[],S=[];for(let g=0;g<_;g++){let M=i._OrtGetInputName(n,g);M===0&&At("Can't get an input name."),d.push(M),v.push(i.UTF8ToString(M))}for(let g=0;gg==="gpu-buffer"||g==="ml-tensor")&&(a=i._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),x={handle:a,outputPreferredLocations:S,outputPreferredLocationsEncoded:S.map(g=>Fd(g))}),Ks.set(n,[n,d,p,x,A,!1]),[n,v,y]}catch(_){throw d.forEach(P=>i._OrtFree(P)),p.forEach(P=>i._OrtFree(P)),a!==0&&i._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&i._OrtReleaseSession(n)!==0&&At("Can't release session."),_}finally{i._free(t),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&At("Can't release session options."),l.forEach(_=>i._free(_)),(w=i.unmountExternalData)==null||w.call(i)}},Nc=e=>{var l;let r=ar(),t=Ks.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,i,n,o,a]=t;o&&(a&&r._OrtClearBoundOutputs(o.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(o.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),i.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&At("Can't release session."),Ks.delete(e)},jc=async(e,r,t,s,i,n=!1)=>{if(!e){r.push(0);return}let o=ar(),a=o.PTR_SIZE,l=e[0],d=e[1],p=e[3],u=p,h,w;if(l==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(n&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let A=e[2].gpuBuffer;w=fn(Rn(l),d);let v=o.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=v(s,i,A,w)}else if(p==="ml-tensor"){let A=e[2].mlTensor;w=fn(Rn(l),d);let v=o.jsepRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=v(s,A,Rn(l),d)}else{let A=e[2];if(Array.isArray(A)){w=a*A.length,h=o._malloc(w),t.push(h);for(let v=0;vo.setValue(P+y*a,v,a===4?"i32":"i64"));let A=o._OrtCreateTensor(Rn(l),h,w,P,d.length,Fd(u));A===0&&At(`Can't create tensor for input/output. session=${s}, index=${i}.`),r.push(A)}finally{o.stackRestore(_)}},Uc=async(e,r,t,s,i,n)=>{var J,q,V;let o=ar(),a=o.PTR_SIZE,l=Ks.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=l[0],p=l[1],u=l[2],h=l[3],w=l[4],_=l[5],P=r.length,A=s.length,v=0,y=[],S=[],x=[],g=[],M=o.stackSave(),E=o.stackAlloc(P*a),k=o.stackAlloc(P*a),B=o.stackAlloc(A*a),R=o.stackAlloc(A*a);try{[v,y]=mp(n);for(let Q=0;QMe*K,1);N=mn(ne);let He=h==null?void 0:h.outputPreferredLocations[s[Q]];if(N==="string"){if(He==="gpu-buffer"||He==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let K=0;K0){let Me=o.jsepGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let K=Me(O),U=fn(ne,ke);if(U===void 0||!Id(N))throw new Error(`Unsupported data type: ${N}`);ge=!0,H.push([N,fe,{gpuBuffer:K,download:o.jsepCreateDownloader(K,U,N),dispose:()=>{o._OrtReleaseTensor(ie)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(He==="ml-tensor"&&ke>0){let Me=o.jsepEnsureTensor;if(!Me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(fn(ne,ke)===void 0||!Ad(N))throw new Error(`Unsupported data type: ${N}`);let K=await Me(e,O,ne,fe,!1);ge=!0,H.push([N,fe,{mlTensor:K,download:o.jsepCreateMLTensorDownloader(O,N),dispose:()=>{o.jsepReleaseTensorId(O),o._OrtReleaseTensor(ie)}},"ml-tensor"])}else{let Me=kd(N),K=new Me(ke);new Uint8Array(K.buffer,K.byteOffset,K.byteLength).set(o.HEAPU8.subarray(O,O+K.byteLength)),H.push([N,fe,K,"cpu"])}}finally{o.stackRestore(le),N==="string"&&O&&o._free(O),ge||o._OrtReleaseTensor(ie),(V=o.jsepOnRunEnd)==null||V.call(o,d)}}return h&&!w&&(o._OrtClearBoundOutputs(h.handle)!==0&&At("Can't clear bound outputs."),Ks.set(e,[d,p,u,h,w,!1])),H}finally{o.stackRestore(M),S.forEach(Y=>o._OrtReleaseTensor(Y)),x.forEach(Y=>o._OrtReleaseTensor(Y)),g.forEach(Y=>o._free(Y)),v!==0&&o._OrtReleaseRunOptions(v),y.forEach(Y=>o._free(Y))}},Vc=e=>{let r=ar(),t=Ks.get(e);if(!t)throw new Error("invalid session id");let s=t[0],i=r._OrtEndProfiling(s);i===0&&At("Can't get an profile file name."),r._OrtFree(i)},Wc=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Hs,Or,Vn,ji,Ui,Oa,Gc,Da,vn,xn,Fw,Ow,Dw,Lw,zw,Bw,Rw,Nw,jw=je(()=>{ss(),Aw(),hn(),Ed(),Hs=()=>!!Vt.wasm.proxy&&typeof document<"u",Vn=!1,ji=!1,Ui=!1,Da=new Map,vn=(e,r)=>{let t=Da.get(e);t?t.push(r):Da.set(e,[r])},xn=()=>{if(Vn||!ji||Ui||!Or)throw new Error("worker not ready")},Fw=e=>{switch(e.data.type){case"init-wasm":Vn=!1,e.data.err?(Ui=!0,Gc[1](e.data.err)):(ji=!0,Gc[0]()),Oa&&(URL.revokeObjectURL(Oa),Oa=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Da.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Ow=async()=>{if(!ji){if(Vn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ui)throw new Error("previous call to 'initWasm()' failed.");if(Vn=!0,Hs())return new Promise((e,r)=>{Or==null||Or.terminate(),cp().then(([t,s])=>{try{Or=s,Or.onerror=n=>r(n),Or.onmessage=Fw,Gc=[e,r];let i={type:"init-wasm",in:Vt};!i.in.wasm.wasmPaths&&(t||bd)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",self.location.href).href}),Or.postMessage(i),Oa=t}catch(i){r(i)}},r)});try{await Sd(Vt.wasm),await zc(Vt),ji=!0}catch(e){throw Ui=!0,e}finally{Vn=!1}}},Dw=async e=>{if(Hs())return xn(),new Promise((r,t)=>{vn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Vt}};Or.postMessage(s)});await Bc(Vt,e)},Lw=async e=>Hs()?(xn(),new Promise((r,t)=>{vn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Or.postMessage(s,[e.buffer])})):Fa(e),zw=async(e,r)=>{if(Hs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xn(),new Promise((t,s)=>{vn("create",[t,s]);let i={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Or.postMessage(i,n)})}else return Rc(e,r)},Bw=async e=>{if(Hs())return xn(),new Promise((r,t)=>{vn("release",[r,t]);let s={type:"release",in:e};Or.postMessage(s)});Nc(e)},Rw=async(e,r,t,s,i,n)=>{if(Hs()){if(t.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return xn(),new Promise((o,a)=>{vn("run",[o,a]);let l=t,d={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Or.postMessage(d,Wc(l))})}else return Uc(e,r,t,s,i,n)},Nw=async e=>{if(Hs())return xn(),new Promise((r,t)=>{vn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Or.postMessage(s)});Vc(e)}}),Kc,Uw,Vw,jv=je(()=>{ss(),jw(),pt(),fd(),Mp(),Kc=(e,r)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Uw=e=>{switch(e[3]){case"cpu":return new ts(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Id(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:i}=e[2];return ts.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:i})}case"ml-tensor":{let r=e[0];if(!Ad(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:i}=e[2];return ts.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Vw=class{async fetchModelAndCopyToWasmMemory(e){return Lw(await Od(e))}async loadModel(e,r){rs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames]=await zw(t,r),Hr()}async dispose(){return Bw(this.sessionId)}async run(e,r,t){rs();let s=[],i=[];Object.entries(e).forEach(u=>{let h=u[0],w=u[1],_=this.inputNames.indexOf(h);if(_===-1)throw new Error(`invalid input '${h}'`);s.push(w),i.push(_)});let n=[],o=[];Object.entries(r).forEach(u=>{let h=u[0],w=u[1],_=this.outputNames.indexOf(h);if(_===-1)throw new Error(`invalid output '${h}'`);n.push(w),o.push(_)});let a=s.map((u,h)=>Kc(u,()=>`input "${this.inputNames[i[h]]}"`)),l=n.map((u,h)=>u?Kc(u,()=>`output "${this.outputNames[o[h]]}"`):null),d=await Rw(this.sessionId,i,a,o,l,t),p={};for(let u=0;uqc,initializeFlags:()=>Hc,wasmBackend:()=>Gw});var Hc,qc,Gw,Uv=je(()=>{ss(),jw(),jv(),Hc=()=>{if((typeof Vt.wasm.initTimeout!="number"||Vt.wasm.initTimeout<0)&&(Vt.wasm.initTimeout=0),Vt.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof Vt.wasm.proxy!="boolean"&&(Vt.wasm.proxy=!1),typeof Vt.wasm.trace!="boolean"&&(Vt.wasm.trace=!1),typeof Vt.wasm.numThreads!="number"||!Number.isInteger(Vt.wasm.numThreads)||Vt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Vt.wasm.numThreads=1;else{let e=typeof navigator>"u"?Cb("node:os").cpus().length:navigator.hardwareConcurrency;Vt.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},qc=class{async init(e){Hc(),await Ow(),await Dw(e)}async createInferenceSessionHandler(e,r){let t=new Vw;return await t.loadModel(e,r),Promise.resolve(t)}},Gw=new qc});ss(),ss(),ss();var Vv="1.22.0-dev.20250306-ccf8fdd9ea",Wv=Zu;{let e=(Uv(),ma(Ww)).wasmBackend;un("webgpu",e,5),un("webnn",e,5),un("cpu",e,10),un("wasm",e,10)}Object.defineProperty(Vt.versions,"web",{value:Vv,enumerable:!0});/** +${n}`,a=t.createShaderModule({code:o,label:e.name});St("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Hr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&t<=i&&s<=i)return[r,t,s];let n=r*t*s,o=Math.ceil(Math.sqrt(n));if(o>i){if(o=Math.ceil(Math.cbrt(n)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),ww,yw,Mw,bw,qv=Ue(()=>{ss(),pt(),ks(),Cp(),sv(),Kv(),Hv(),ww=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{var i,n;let s=e.name;return(i=e.shaderCache)!=null&&i.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${ww(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Mw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},bw=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=n=>r.features.has(n)&&t.push(n)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Mw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Ip(this),this.programManager=new gw(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ld(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;rs(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=w);let P=Number(w-this.queryTimeBase),A=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(P)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map(b=>({dims:b.dims,dataType:mn(b.dataType)})),outputsMetadata:h.map(b=>({dims:b.dims,dataType:mn(b.dataType)})),kernelId:o,kernelType:l,kernelName:d,programName:p,startTime:P,endTime:A});else{let b="";u.forEach(($,T)=>{b+=`input[${T}]: [${$.dims}] | ${mn($.dataType)}, `});let y="";h.forEach(($,T)=>{y+=`output[${T}]: [${$.dims}] | ${mn($.dataType)}, `}),console.log(`[profiling] kernel "${o}|${l}|${d}|${p}" ${b}${y}execution time: ${A-P} ns`)}ki("GPU",`${p}::${w}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),Hr()}run(e,r,t,s,i,n){rs(e.name);let o=[];for(let y=0;y$):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let u=[],h=[];for(let y=0;y=n)throw new Error(`Invalid output index: ${p[y]}`);if(p[y]===-3)continue;let $=p[y]===-1,T=p[y]===-2,g=$||T?i(a[y].dataType,a[y].dims):s(p[y],a[y].dataType,a[y].dims);if(u.push(g),g.data===0)continue;let M=this.gpuDataManager.get(g.data);if(!M)throw new Error(`no GPU data for output: ${g.data}`);if($&&this.temporaryData.push(M),T){let E=this.kernelPersistentData.get(this.currentKernelId);E||(E=[],this.kernelPersistentData.set(this.currentKernelId,E)),E.push(M)}h.push(M)}if(o.length!==r.length||h.length!==u.length){if(h.length===0)return Hr(e.name),u;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let w;if(d){let y=0,$=[];d.forEach(E=>{let k=typeof E.data=="number"?[E.data]:E.data;if(k.length===0)return;let B=E.type===10?2:4,N,J;E.type===10?(J=k.length>4?16:k.length>2?8:k.length*B,N=k.length>4?16:B*k.length):(J=k.length<=2?k.length*B:16,N=16),y=Math.ceil(y/J)*J,$.push(y);let q=E.type===10?8:4;y+=k.length>4?Math.ceil(k.length/q)*N:k.length*B});let T=16;y=Math.ceil(y/T)*T;let g=new ArrayBuffer(y);d.forEach((E,k)=>{let B=$[k],N=typeof E.data=="number"?[E.data]:E.data;if(E.type===6)new Int32Array(g,B,N.length).set(N);else if(E.type===12)new Uint32Array(g,B,N.length).set(N);else if(E.type===10)new Uint16Array(g,B,N.length).set(N);else if(E.type===1)new Float32Array(g,B,N.length).set(N);else throw new Error(`Unsupported uniform type: ${mn(E.type)}`)});let M=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,g,0,y),this.gpuDataManager.release(M.id),w={offset:0,size:y,buffer:M.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),P=f[1]===1&&f[2]===1,A=yw(e,r,P),b=this.programManager.getArtifact(A);if(b||(b=this.programManager.build(e,f),this.programManager.setArtifact(A,b),St("info",()=>`[artifact] key: ${A}, programName: ${e.name}`)),d&&b.uniformVariablesInfo){if(d.length!==b.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${b.uniformVariablesInfo.length}, got ${d.length} in program "${b.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${A}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:b.programInfo.name,inputTensorViews:r,outputTensorViews:u};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(b,o,h,f,w),Hr(e.name),u}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let i=fw.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let i=s.kernelType,n=s.kernelName,o=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),St("info",()=>`[WebGPU] Start to run kernel "[${i}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),o(r,a[1]),0}catch(d){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${n}" failed. ${d}`)),1}finally{l&&t.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${i}] ${n}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let n=i.get(r),o=this.gpuDataManager.registerExternalBuffer(t,s,n);return i.set(r,[o,t]),o}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await jd(this,e,r);return zd(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){St("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){St("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){St("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),vw,Oc,xw,Dc,Lc,zc,Tw,Ew,Qv=Ue(()=>{ks(),vw=1,Oc=()=>vw++,xw=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Dc=(e,r)=>{let t=xw.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,i)=>s*i)*t/8):0},Lc=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Dc(this.dataType,this.tensorShape)}destroy(){St("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,i)=>s===t[i])}},zc=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let i=this.tensorManager.getMLContext(e);if(this.wrapper){if(this.wrapper.canReuseTensor(i,r,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Dc(r,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,r,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else St("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Tw=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=Oc();return this.tensorTrackersById.set(e,new zc(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,i){St("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${i}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,i)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){St("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let i=this.getMLContext(e),n=Oc(),o=new Lc({sessionId:e,context:i,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new zc(this,o)),this.externalTensors.add(o),n}async getCachedTensor(e,r,t,s,i,n){let o=this.getMLContext(e);for(let[l,d]of this.freeTensors.entries())if(d.canReuseTensor(o,r,t)){St("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let p=this.freeTensors.splice(l,1)[0];return p.sessionId=e,p}St("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let a=await o.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:i,readable:n});return new Lc({sessionId:e,context:o,tensor:a,dataType:r,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Ew=(...e)=>new Tw(...e)}),Ia,Pw,Cw,Xv=Ue(()=>{pt(),hn(),Cp(),Qv(),ks(),Ia=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Pw=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((i,n)=>i===s[n]&&e[i]===r[i])},Cw=class{constructor(e){this.tensorManager=Ew(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ld(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){St("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){St("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)St("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>Pw(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(i=>i.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){St("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,i){let n=Ia.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,i)}async createTemporaryTensor(e,r,t){St("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Ia.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,r){if(!ar().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");St("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return zd(t,r)}}registerMLTensor(e,r,t,s){let i=Ia.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,i,s);return St("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,i,n){if(!n)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let a=n.get(o);if(!a)throw new Error(`File with name ${o} not found in preloaded files.`);if(r+t>a.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l=a.slice(r,r+t).buffer,d;switch(i.dataType){case"float32":d=new Float32Array(l);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case"int32":d=new Int32Array(l);break;case"uint32":d=new Uint32Array(l);break;case"int64":d=new BigInt64Array(l);break;case"uint64":d=new BigUint64Array(l);break;case"int8":d=new Int8Array(l);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(l);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return St("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),s.constant(i,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}flush(){}}}),Sw={};Ci(Sw,{init:()=>kw});var Aa,$w,kw,Jv=Ue(()=>{pt(),qv(),ks(),Mt(),Xv(),Aa=class yb{constructor(r,t,s,i){this.module=r,this.dataType=t,this.data=s,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(xe.size(r)!==xe.size(this.dims))throw new Error("Invalid new shape");return new yb(this.module,this.dataType,this.data,r)}},$w=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,i=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*i++,n));let o=Number(e.getValue(s*i++,n));this.outputCount=Number(e.getValue(s*i++,n)),this.customDataOffset=Number(e.getValue(s*i++,"*")),this.customDataSize=Number(e.getValue(s*i++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],i=(a,l,d)=>new Aa(this.module,l,this.output(a,d),d),n=(a,l)=>{let d=_n(a,l);if(!d)throw new Error(`Unsupported data type: ${a}`);let p=d>0?this.backend.gpuDataManager.create(d).id:0;return new Aa(this.module,a,p,l)};return this.backend.run(e,t,s,i,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,i=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,i);for(let o=0;o{let i=r.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=new bw;await n.initialize(t,s),i("webgpu",[n,o=>n.alloc(Number(o)),o=>n.free(o),(o,a,l,d=!1)=>{if(d)St("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(a)}, size=${Number(l)}`),n.memcpy(Number(o),Number(a));else{St("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(a)}, size=${Number(l)}`);let p=r.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(l));n.upload(Number(a),p)}},async(o,a,l)=>{St("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${a}, size=${l}`),await n.download(Number(o),()=>r.HEAPU8.subarray(Number(a)>>>0,Number(a+l)>>>0))},(o,a,l)=>n.createKernel(o,Number(a),l,r.UTF8ToString(r._JsepGetNodeName(Number(a)))),o=>n.releaseKernel(o),(o,a,l,d)=>{St("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${o}, contextDataOffset=${a}`);let p=new $w(r,n,Number(a));return n.computeKernel(Number(o),p,d)},()=>n.captureBegin(),()=>n.captureEnd(),()=>n.replay()])}else{let n=new Cw(t);i("webnn",[n,()=>n.reserveTensorId(),o=>n.releaseTensorId(o),async(o,a,l,d,p)=>n.ensureTensor(o,a,l,d,p),(o,a)=>{n.uploadTensor(o,a)},async(o,a)=>n.downloadTensor(o,a)])}}}),Iw,Bc,Rc,Ks,Aw,Fa,Nc,jc,Uc,Vc,Wc,Gc,Fw=Ue(()=>{tv(),rv(),pt(),hn(),kd(),bp(),Iw=(e,r)=>{ar()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},Bc=async e=>{Iw(e.wasm.numThreads,ya(e.logLevel))},Rc=async(e,r)=>{{let t=(Jv(),ma(Sw)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:n}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",ar(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",ar(),e)}}},Ks=new Map,Aw=e=>{let r=ar(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,i,i+s)!==0&&At("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(i,n)),Number(r.getValue(i+s,n))]}finally{r.stackRestore(t)}},Fa=e=>{let r=ar(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},Nc=async(e,r)=>{var u,h,w;let t,s,i=ar();Array.isArray(e)?[t,s]=e:e.buffer===i.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=Fa(e);let n=0,o=0,a=0,l=[],d=[],p=[];try{if([o,l]=Mp(r),(r==null?void 0:r.externalData)&&i.mountExternalData){let g=[];for(let M of r.externalData){let E=typeof M=="string"?M:M.path;g.push(Dd(typeof M=="string"?M:M.data).then(k=>{i.mountExternalData(E,k)}))}await Promise.all(g)}for(let g of(r==null?void 0:r.executionProviders)??[])if((typeof g=="string"?g:g.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof g!="string"){let M=g,E=M==null?void 0:M.context,k=M==null?void 0:M.gpuDevice,B=M==null?void 0:M.deviceType,N=M==null?void 0:M.powerPreference;E?i.currentContext=E:k?i.currentContext=await i.jsepCreateMLContext(k):i.currentContext=await i.jsepCreateMLContext({deviceType:B,powerPreference:N})}else i.currentContext=await i.jsepCreateMLContext();break}n=await i._OrtCreateSession(t,s,o),n===0&&At("Can't create a session."),(u=i.jsepOnCreateSession)==null||u.call(i),i.currentContext&&(i.jsepRegisterMLContext(n,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[f,P]=Aw(n),A=!!(r!=null&&r.enableGraphCapture),b=[],y=[],$=[];for(let g=0;gg==="gpu-buffer"||g==="ml-tensor")&&(a=i._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),T={handle:a,outputPreferredLocations:$,outputPreferredLocationsEncoded:$.map(g=>Od(g))}),Ks.set(n,[n,d,p,T,A,!1]),[n,b,y]}catch(f){throw d.forEach(P=>i._OrtFree(P)),p.forEach(P=>i._OrtFree(P)),a!==0&&i._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&i._OrtReleaseSession(n)!==0&&At("Can't release session."),f}finally{i._free(t),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&At("Can't release session options."),l.forEach(f=>i._free(f)),(w=i.unmountExternalData)==null||w.call(i)}},jc=e=>{var l;let r=ar(),t=Ks.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,i,n,o,a]=t;o&&(a&&r._OrtClearBoundOutputs(o.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(o.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),i.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&At("Can't release session."),Ks.delete(e)},Uc=async(e,r,t,s,i,n=!1)=>{if(!e){r.push(0);return}let o=ar(),a=o.PTR_SIZE,l=e[0],d=e[1],p=e[3],u=p,h,w;if(l==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(n&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let A=e[2].gpuBuffer;w=_n(Rn(l),d);let b=o.jsepRegisterBuffer;if(!b)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=b(s,i,A,w)}else if(p==="ml-tensor"){let A=e[2].mlTensor;w=_n(Rn(l),d);let b=o.jsepRegisterMLTensor;if(!b)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=b(s,A,Rn(l),d)}else{let A=e[2];if(Array.isArray(A)){w=a*A.length,h=o._malloc(w),t.push(h);for(let b=0;bo.setValue(P+y*a,b,a===4?"i32":"i64"));let A=o._OrtCreateTensor(Rn(l),h,w,P,d.length,Od(u));A===0&&At(`Can't create tensor for input/output. session=${s}, index=${i}.`),r.push(A)}finally{o.stackRestore(f)}},Vc=async(e,r,t,s,i,n)=>{var J,q,V;let o=ar(),a=o.PTR_SIZE,l=Ks.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=l[0],p=l[1],u=l[2],h=l[3],w=l[4],f=l[5],P=r.length,A=s.length,b=0,y=[],$=[],T=[],g=[],M=o.stackSave(),E=o.stackAlloc(P*a),k=o.stackAlloc(P*a),B=o.stackAlloc(A*a),N=o.stackAlloc(A*a);try{[b,y]=_p(n);for(let Q=0;QMe*K,1);R=mn(ne);let He=h==null?void 0:h.outputPreferredLocations[s[Q]];if(R==="string"){if(He==="gpu-buffer"||He==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let K=0;K0){let Me=o.jsepGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let K=Me(O),U=_n(ne,ke);if(U===void 0||!Ad(R))throw new Error(`Unsupported data type: ${R}`);we=!0,H.push([R,_e,{gpuBuffer:K,download:o.jsepCreateDownloader(K,U,R),dispose:()=>{o._OrtReleaseTensor(ie)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(He==="ml-tensor"&&ke>0){let Me=o.jsepEnsureTensor;if(!Me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(_n(ne,ke)===void 0||!Fd(R))throw new Error(`Unsupported data type: ${R}`);let K=await Me(e,O,ne,_e,!1);we=!0,H.push([R,_e,{mlTensor:K,download:o.jsepCreateMLTensorDownloader(O,R),dispose:()=>{o.jsepReleaseTensorId(O),o._OrtReleaseTensor(ie)}},"ml-tensor"])}else{let Me=Id(R),K=new Me(ke);new Uint8Array(K.buffer,K.byteOffset,K.byteLength).set(o.HEAPU8.subarray(O,O+K.byteLength)),H.push([R,_e,K,"cpu"])}}finally{o.stackRestore(le),R==="string"&&O&&o._free(O),we||o._OrtReleaseTensor(ie),(V=o.jsepOnRunEnd)==null||V.call(o,d)}}return h&&!w&&(o._OrtClearBoundOutputs(h.handle)!==0&&At("Can't clear bound outputs."),Ks.set(e,[d,p,u,h,w,!1])),H}finally{o.stackRestore(M),$.forEach(Y=>o._OrtReleaseTensor(Y)),T.forEach(Y=>o._OrtReleaseTensor(Y)),g.forEach(Y=>o._free(Y)),b!==0&&o._OrtReleaseRunOptions(b),y.forEach(Y=>o._free(Y))}},Wc=e=>{let r=ar(),t=Ks.get(e);if(!t)throw new Error("invalid session id");let s=t[0],i=r._OrtEndProfiling(s);i===0&&At("Can't get an profile file name."),r._OrtFree(i)},Gc=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Hs,Or,Vn,ji,Ui,Oa,Kc,Da,vn,xn,Ow,Dw,Lw,zw,Bw,Rw,Nw,jw,Uw=Ue(()=>{ss(),Fw(),hn(),Pd(),Hs=()=>!!Vt.wasm.proxy&&typeof document<"u",Vn=!1,ji=!1,Ui=!1,Da=new Map,vn=(e,r)=>{let t=Da.get(e);t?t.push(r):Da.set(e,[r])},xn=()=>{if(Vn||!ji||Ui||!Or)throw new Error("worker not ready")},Ow=e=>{switch(e.data.type){case"init-wasm":Vn=!1,e.data.err?(Ui=!0,Kc[1](e.data.err)):(ji=!0,Kc[0]()),Oa&&(URL.revokeObjectURL(Oa),Oa=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Da.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Dw=async()=>{if(!ji){if(Vn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ui)throw new Error("previous call to 'initWasm()' failed.");if(Vn=!0,Hs())return new Promise((e,r)=>{Or==null||Or.terminate(),up().then(([t,s])=>{try{Or=s,Or.onerror=n=>r(n),Or.onmessage=Ow,Kc=[e,r];let i={type:"init-wasm",in:Vt};!i.in.wasm.wasmPaths&&(t||vd)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",self.location.href).href}),Or.postMessage(i),Oa=t}catch(i){r(i)}},r)});try{await $d(Vt.wasm),await Bc(Vt),ji=!0}catch(e){throw Ui=!0,e}finally{Vn=!1}}},Lw=async e=>{if(Hs())return xn(),new Promise((r,t)=>{vn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Vt}};Or.postMessage(s)});await Rc(Vt,e)},zw=async e=>Hs()?(xn(),new Promise((r,t)=>{vn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Or.postMessage(s,[e.buffer])})):Fa(e),Bw=async(e,r)=>{if(Hs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xn(),new Promise((t,s)=>{vn("create",[t,s]);let i={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Or.postMessage(i,n)})}else return Nc(e,r)},Rw=async e=>{if(Hs())return xn(),new Promise((r,t)=>{vn("release",[r,t]);let s={type:"release",in:e};Or.postMessage(s)});jc(e)},Nw=async(e,r,t,s,i,n)=>{if(Hs()){if(t.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return xn(),new Promise((o,a)=>{vn("run",[o,a]);let l=t,d={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Or.postMessage(d,Gc(l))})}else return Vc(e,r,t,s,i,n)},jw=async e=>{if(Hs())return xn(),new Promise((r,t)=>{vn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Or.postMessage(s)});Wc(e)}}),Hc,Vw,Ww,Yv=Ue(()=>{ss(),Uw(),pt(),fd(),bp(),Hc=(e,r)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Vw=e=>{switch(e[3]){case"cpu":return new ts(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Ad(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:i}=e[2];return ts.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:i})}case"ml-tensor":{let r=e[0];if(!Fd(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:i}=e[2];return ts.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Ww=class{async fetchModelAndCopyToWasmMemory(e){return zw(await Dd(e))}async loadModel(e,r){rs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames]=await Bw(t,r),Hr()}async dispose(){return Rw(this.sessionId)}async run(e,r,t){rs();let s=[],i=[];Object.entries(e).forEach(u=>{let h=u[0],w=u[1],f=this.inputNames.indexOf(h);if(f===-1)throw new Error(`invalid input '${h}'`);s.push(w),i.push(f)});let n=[],o=[];Object.entries(r).forEach(u=>{let h=u[0],w=u[1],f=this.outputNames.indexOf(h);if(f===-1)throw new Error(`invalid output '${h}'`);n.push(w),o.push(f)});let a=s.map((u,h)=>Hc(u,()=>`input "${this.inputNames[i[h]]}"`)),l=n.map((u,h)=>u?Hc(u,()=>`output "${this.outputNames[o[h]]}"`):null),d=await Nw(this.sessionId,i,a,o,l,t),p={};for(let u=0;uQc,initializeFlags:()=>qc,wasmBackend:()=>Kw});var qc,Qc,Kw,Zv=Ue(()=>{ss(),Uw(),Yv(),qc=()=>{if((typeof Vt.wasm.initTimeout!="number"||Vt.wasm.initTimeout<0)&&(Vt.wasm.initTimeout=0),Vt.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof Vt.wasm.proxy!="boolean"&&(Vt.wasm.proxy=!1),typeof Vt.wasm.trace!="boolean"&&(Vt.wasm.trace=!1),typeof Vt.wasm.numThreads!="number"||!Number.isInteger(Vt.wasm.numThreads)||Vt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Vt.wasm.numThreads=1;else{let e=typeof navigator>"u"?Bb("node:os").cpus().length:navigator.hardwareConcurrency;Vt.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Qc=class{async init(e){qc(),await Dw(),await Lw(e)}async createInferenceSessionHandler(e,r){let t=new Ww;return await t.loadModel(e,r),Promise.resolve(t)}},Kw=new Qc});ss(),ss(),ss();var ex="1.22.0-dev.20250306-ccf8fdd9ea",tx=ep;{let e=(Zv(),ma(Gw)).wasmBackend;un("webgpu",e,5),un("webnn",e,5),un("cpu",e,10),un("wasm",e,10)}Object.defineProperty(Vt.versions,"web",{value:ex,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -2827,20 +2827,20 @@ ${n}`,a=t.createShaderModule({code:o,label:e.name});St("verbose",()=>`[WebGPU] $ * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= - */var Gv=Object.freeze({__proto__:null,get InferenceSession(){return md},get TRACE(){return ki},get TRACE_FUNC_BEGIN(){return rs},get TRACE_FUNC_END(){return Hr},get Tensor(){return ts},default:Wv,get env(){return Vt},get registerBackend(){return un}}),As={},Kv={"onnxruntime-common":e=>{e.exports=xb},"onnxruntime-web":e=>{e.exports=Gv},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Fe,Interpreter:()=>Ie,Template:()=>Ve,parse:()=>N,tokenize:()=>u});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),i=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(D,Z){this.value=D,this.type=Z}};function o(D){return/\w/.test(D)}function a(D){return/[0-9]/.test(D)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],d=new Map([["n",` + */var rx=Object.freeze({__proto__:null,get InferenceSession(){return _d},get TRACE(){return ki},get TRACE_FUNC_BEGIN(){return rs},get TRACE_FUNC_END(){return Hr},get Tensor(){return ts},default:tx,get env(){return Vt},get registerBackend(){return un}}),As={},sx={"onnxruntime-common":e=>{e.exports=Ob},"onnxruntime-web":e=>{e.exports=rx},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Ae,Interpreter:()=>Ie,Template:()=>Ve,parse:()=>R,tokenize:()=>u});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),i=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(D,Z){this.value=D,this.type=Z}};function o(D){return/\w/.test(D)}function a(D){return/[0-9]/.test(D)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],d=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(D,Z={}){return D.endsWith(` -`)&&(D=D.slice(0,-1)),D=D.replace(/{#.*?#}/gs,"{##}"),Z.lstrip_blocks&&(D=D.replace(/^[ \t]*({[#%])/gm,"$1")),Z.trim_blocks&&(D=D.replace(/([#%]})\n/g,"$1")),D.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function u(D,Z={}){var ve,Re,Ae;const z=[],ee=p(D,Z);let ce=0;const be=Ue=>{let Qe="";for(;Ue(ee[ce]);){if(ee[ce]==="\\"){if(++ce,ce>=ee.length)throw new SyntaxError("Unexpected end of input");const Xe=ee[ce++],ct=d.get(Xe);if(ct===void 0)throw new SyntaxError(`Unexpected escaped character: ${Xe}`);Qe+=ct;continue}if(Qe+=ee[ce++],ce>=ee.length)throw new SyntaxError("Unexpected end of input")}return Qe};e:for(;ce0){z.push(new n(Xe,s.Text));continue}}be(Xe=>/\s/.test(Xe));const Qe=ee[ce];if(Qe==="-"||Qe==="+"){const Xe=(Re=z.at(-1))==null?void 0:Re.type;if(Xe===s.Text||Xe===void 0)throw new SyntaxError(`Unexpected character: ${Qe}`);switch(Xe){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++ce;const ct=be(a);z.push(new n(`${Qe}${ct}`,ct.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Xe,ct]of l)if(ee.slice(ce,ce+Xe.length)===Xe){z.push(new n(Xe,ct)),ce+=Xe.length;continue e}if(Qe==="'"||Qe==='"'){++ce;const Xe=be(ct=>ct!==Qe);z.push(new n(Xe,s.StringLiteral)),++ce;continue}if(a(Qe)){const Xe=be(a);z.push(new n(Xe,s.NumericLiteral));continue}if(o(Qe)){const Xe=be(o),ct=Object.hasOwn(i,Xe)?i[Xe]:s.Identifier;ct===s.In&&((Ae=z.at(-1))==null?void 0:Ae.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Xe,ct));continue}throw new SyntaxError(`Unexpected character: ${Qe}`)}return z}var h=class{constructor(){re(this,"type","Statement")}},w=class extends h{constructor(Z){super();re(this,"type","Program");this.body=Z}},_=class extends h{constructor(Z,z,ee){super();re(this,"type","If");this.test=Z,this.body=z,this.alternate=ee}},P=class extends h{constructor(Z,z,ee,ce){super();re(this,"type","For");this.loopvar=Z,this.iterable=z,this.body=ee,this.defaultBlock=ce}},A=class extends h{constructor(Z,z){super();re(this,"type","Set");this.assignee=Z,this.value=z}},v=class extends h{constructor(Z,z,ee){super();re(this,"type","Macro");this.name=Z,this.args=z,this.body=ee}},y=class extends h{constructor(){super(...arguments);re(this,"type","Expression")}},S=class extends y{constructor(Z,z,ee){super();re(this,"type","MemberExpression");this.object=Z,this.property=z,this.computed=ee}},x=class extends y{constructor(Z,z){super();re(this,"type","CallExpression");this.callee=Z,this.args=z}},g=class extends y{constructor(Z){super();re(this,"type","Identifier");this.value=Z}},M=class extends y{constructor(Z){super();re(this,"type","Literal");this.value=Z}},E=class extends M{constructor(){super(...arguments);re(this,"type","NumericLiteral")}},k=class extends M{constructor(){super(...arguments);re(this,"type","StringLiteral")}},B=class extends M{constructor(){super(...arguments);re(this,"type","BooleanLiteral")}},R=class extends M{constructor(){super(...arguments);re(this,"type","NullLiteral")}},J=class extends M{constructor(){super(...arguments);re(this,"type","ArrayLiteral")}},q=class extends M{constructor(){super(...arguments);re(this,"type","TupleLiteral")}},V=class extends M{constructor(){super(...arguments);re(this,"type","ObjectLiteral")}},Y=class extends y{constructor(Z,z,ee){super();re(this,"type","BinaryExpression");this.operator=Z,this.left=z,this.right=ee}},H=class extends y{constructor(Z,z){super();re(this,"type","FilterExpression");this.operand=Z,this.filter=z}},Q=class extends y{constructor(Z,z){super();re(this,"type","SelectExpression");this.iterable=Z,this.test=z}},ie=class extends y{constructor(Z,z,ee){super();re(this,"type","TestExpression");this.operand=Z,this.negate=z,this.test=ee}},le=class extends y{constructor(Z,z){super();re(this,"type","UnaryExpression");this.operator=Z,this.argument=z}},ae=class extends y{constructor(Z=void 0,z=void 0,ee=void 0){super();re(this,"type","SliceExpression");this.start=Z,this.stop=z,this.step=ee}},ge=class extends y{constructor(Z,z){super();re(this,"type","KeywordArgumentExpression");this.key=Z,this.value=z}};function N(D){const Z=new w([]);let z=0;function ee(Be,et){const it=D[z++];if(!it||it.type!==Be)throw new Error(`Parser Error: ${et}. ${it.type} !== ${Be}.`);return it}function ce(){switch(D[z].type){case s.Text:return Re();case s.OpenStatement:return Ae();case s.OpenExpression:return Ue();default:throw new SyntaxError(`Unexpected token type: ${D[z].type}`)}}function be(...Be){return z+Be.length<=D.length&&Be.some((et,it)=>et!==D[z+it].type)}function ve(...Be){return z+Be.length<=D.length&&Be.every((et,it)=>et===D[z+it].type)}function Re(){return new k(ee(s.Text,"Expected text token").value)}function Ae(){ee(s.OpenStatement,"Expected opening statement token");let Be;switch(D[z].type){case s.Set:++z,Be=Qe(),ee(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,Be=Xe(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndIf,"Expected endif token"),ee(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,Be=ct(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndMacro,"Expected endmacro token"),ee(s.CloseStatement,"Expected %} token");break;case s.For:++z,Be=nr(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndFor,"Expected endfor token"),ee(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${D[z].type}`)}return Be}function Ue(){ee(s.OpenExpression,"Expected opening expression token");const Be=jt();return ee(s.CloseExpression,"Expected closing expression token"),Be}function Qe(){const Be=jt();if(ve(s.Equals)){++z;const et=Qe();return new A(Be,et)}return Be}function Xe(){var rr,zt,kr,ps,hs,Er,ms,fs;const Be=jt();ee(s.CloseStatement,"Expected closing statement token");const et=[],it=[];for(;!(((rr=D[z])==null?void 0:rr.type)===s.OpenStatement&&(((zt=D[z+1])==null?void 0:zt.type)===s.ElseIf||((kr=D[z+1])==null?void 0:kr.type)===s.Else||((ps=D[z+1])==null?void 0:ps.type)===s.EndIf));)et.push(ce());if(((hs=D[z])==null?void 0:hs.type)===s.OpenStatement&&((Er=D[z+1])==null?void 0:Er.type)!==s.EndIf)if(++z,ve(s.ElseIf))ee(s.ElseIf,"Expected elseif token"),it.push(Xe());else for(ee(s.Else,"Expected else token"),ee(s.CloseStatement,"Expected closing statement token");!(((ms=D[z])==null?void 0:ms.type)===s.OpenStatement&&((fs=D[z+1])==null?void 0:fs.type)===s.EndIf);)it.push(ce());return new _(Be,et,it)}function ct(){const Be=mr();if(Be.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const et=qr();ee(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndMacro);)it.push(ce());return new v(Be,et,it)}function xt(Be=!1){const et=Be?mr:jt,it=[et()],rr=ve(s.Comma);for(;rr&&(++z,it.push(et()),!!ve(s.Comma)););return rr?new q(it):it[0]}function nr(){const Be=xt(!0);if(!(Be instanceof g||Be instanceof q))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Be.type} instead`);ee(s.In,"Expected `in` keyword following loop variable");const et=jt();ee(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndFor)&&be(s.OpenStatement,s.Else);)it.push(ce());const rr=[];if(ve(s.OpenStatement,s.Else))for(++z,++z,ee(s.CloseStatement,"Expected closing statement token");be(s.OpenStatement,s.EndFor);)rr.push(ce());return new P(Be,et,it,rr)}function jt(){return dr()}function dr(){const Be=ds();if(ve(s.If)){++z;const et=ds();if(ve(s.Else)){++z;const it=ds();return new _(et,[Be],[it])}else return new Q(Be,et)}return Be}function ds(){let Be=Fs();for(;ve(s.Or);){const et=D[z];++z;const it=Fs();Be=new Y(et,Be,it)}return Be}function Fs(){let Be=Dr();for(;ve(s.And);){const et=D[z];++z;const it=Dr();Be=new Y(et,Be,it)}return Be}function Dr(){let Be;for(;ve(s.Not);){const et=D[z];++z;const it=Dr();Be=new le(et,it)}return Be??cs()}function cs(){let Be=Os();for(;ve(s.ComparisonBinaryOperator)||ve(s.In)||ve(s.NotIn);){const et=D[z];++z;const it=Os();Be=new Y(et,Be,it)}return Be}function Os(){let Be=Ts();for(;ve(s.AdditiveBinaryOperator);){const et=D[z];++z;const it=Ts();Be=new Y(et,Be,it)}return Be}function jr(){const Be=xs(mr());return ve(s.OpenParen)?dt(Be):Be}function dt(Be){let et=new x(Be,qr());return et=xs(et),ve(s.OpenParen)&&(et=dt(et)),et}function qr(){ee(s.OpenParen,"Expected opening parenthesis for arguments list");const Be=Ur();return ee(s.CloseParen,"Expected closing parenthesis for arguments list"),Be}function Ur(){const Be=[];for(;!ve(s.CloseParen);){let et=jt();if(ve(s.Equals)){if(++z,!(et instanceof g))throw new SyntaxError("Expected identifier for keyword argument");const it=jt();et=new ge(et,it)}Be.push(et),ve(s.Comma)&&++z}return Be}function us(){const Be=[];let et=!1;for(;!ve(s.CloseSquareBracket);)ve(s.Colon)?(Be.push(void 0),++z,et=!0):(Be.push(jt()),ve(s.Colon)&&(++z,et=!0));if(Be.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(et){if(Be.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ae(...Be)}return Be[0]}function xs(Be){for(;ve(s.Dot)||ve(s.OpenSquareBracket);){const et=D[z];++z;let it;const rr=et.type!==s.Dot;if(rr)it=us(),ee(s.CloseSquareBracket,"Expected closing square bracket");else if(it=mr(),it.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Be=new S(Be,it,rr)}return Be}function Ts(){let Be=Es();for(;ve(s.MultiplicativeBinaryOperator);){const et=D[z];++z;const it=Es();Be=new Y(et,Be,it)}return Be}function Es(){let Be=Ds();for(;ve(s.Is);){++z;const et=ve(s.Not);et&&++z;let it=mr();if(it instanceof B?it=new g(it.value.toString()):it instanceof R&&(it=new g("none")),!(it instanceof g))throw new SyntaxError("Expected identifier for the test");Be=new ie(Be,et,it)}return Be}function Ds(){let Be=jr();for(;ve(s.Pipe);){++z;let et=mr();if(!(et instanceof g))throw new SyntaxError("Expected identifier for the filter");ve(s.OpenParen)&&(et=dt(et)),Be=new H(Be,et)}return Be}function mr(){const Be=D[z];switch(Be.type){case s.NumericLiteral:return++z,new E(Number(Be.value));case s.StringLiteral:return++z,new k(Be.value);case s.BooleanLiteral:return++z,new B(Be.value.toLowerCase()==="true");case s.NullLiteral:return++z,new R(null);case s.Identifier:return++z,new g(Be.value);case s.OpenParen:{++z;const et=xt();if(D[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${D[z].type} instead`);return++z,et}case s.OpenSquareBracket:{++z;const et=[];for(;!ve(s.CloseSquareBracket);)et.push(jt()),ve(s.Comma)&&++z;return++z,new J(et)}case s.OpenCurlyBracket:{++z;const et=new Map;for(;!ve(s.CloseCurlyBracket);){const it=jt();ee(s.Colon,"Expected colon between key and value in object literal");const rr=jt();et.set(it,rr),ve(s.Comma)&&++z}return++z,new V(et)}default:throw new SyntaxError(`Unexpected token: ${Be.type}`)}}for(;z=0?(Z=(Z??(Z=0))<0?Math.max(D.length+Z,0):Math.min(Z,D.length),z=(z??(z=D.length))<0?Math.max(D.length+z,0):Math.min(z,D.length)):(Z=(Z??(Z=D.length-1))<0?Math.max(D.length+Z,-1):Math.min(Z,D.length-1),z=(z??(z=-1))<-1?Math.max(D.length+z,-1):Math.min(z,D.length-1));const be=[];for(let ve=Z;ce*veZ.toUpperCase())}var X=class{constructor(D=void 0){re(this,"type","RuntimeValue");re(this,"value");re(this,"builtins",new Map);this.value=D}__bool__(){return new ke(!!this.value)}},we=class extends X{constructor(){super(...arguments);re(this,"type","NumericValue")}},fe=class extends X{constructor(){super(...arguments);re(this,"type","StringValue");re(this,"builtins",new Map([["upper",new pe(()=>new fe(this.value.toUpperCase()))],["lower",new pe(()=>new fe(this.value.toLowerCase()))],["strip",new pe(()=>new fe(this.value.trim()))],["title",new pe(()=>new fe(ne(this.value)))],["length",new we(this.value.length)],["rstrip",new pe(()=>new fe(this.value.trimEnd()))],["lstrip",new pe(()=>new fe(this.value.trimStart()))],["split",new pe(Z=>{const z=Z[0]??new Pe;if(!(z instanceof fe||z instanceof Pe))throw new Error("sep argument must be a string or null");const ee=Z[1]??new we(-1);if(!(ee instanceof we))throw new Error("maxsplit argument must be a number");let ce=[];if(z instanceof Pe){const be=this.value.trimStart();for(const{0:ve,index:Re}of be.matchAll(/\S+/g)){if(ee.value!==-1&&ce.length>=ee.value&&Re!==void 0){ce.push(ve+be.slice(Re+ve.length));break}ce.push(ve)}}else{if(z.value==="")throw new Error("empty separator");ce=this.value.split(z.value),ee.value!==-1&&ce.length>ee.value&&ce.push(ce.splice(ee.value).join(z.value))}return new K(ce.map(be=>new fe(be)))})]]))}},ke=class extends X{constructor(){super(...arguments);re(this,"type","BooleanValue")}},He=class extends X{constructor(){super(...arguments);re(this,"type","ObjectValue");re(this,"builtins",new Map([["get",new pe(([Z,z])=>{if(!(Z instanceof fe))throw new Error(`Object key must be a string: got ${Z.type}`);return this.value.get(Z.value)??z??new Pe})],["items",new pe(()=>new K(Array.from(this.value.entries()).map(([Z,z])=>new K([new fe(Z),z]))))]]))}__bool__(){return new ke(this.value.size>0)}},Me=class extends He{constructor(){super(...arguments);re(this,"type","KeywordArgumentsValue")}},K=class extends X{constructor(){super(...arguments);re(this,"type","ArrayValue");re(this,"builtins",new Map([["length",new we(this.value.length)]]))}__bool__(){return new ke(this.value.length>0)}},U=class extends K{constructor(){super(...arguments);re(this,"type","TupleValue")}},pe=class extends X{constructor(){super(...arguments);re(this,"type","FunctionValue")}},Pe=class extends X{constructor(){super(...arguments);re(this,"type","NullValue")}},Ee=class extends X{constructor(){super(...arguments);re(this,"type","UndefinedValue")}},Fe=class{constructor(D){re(this,"variables",new Map([["namespace",new pe(D=>{if(D.length===0)return new He(new Map);if(D.length!==1||!(D[0]instanceof He))throw new Error("`namespace` expects either zero arguments or a single object argument");return D[0]})]]));re(this,"tests",new Map([["boolean",D=>D.type==="BooleanValue"],["callable",D=>D instanceof pe],["odd",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${D.type}`);return D.value%2!==0}],["even",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${D.type}`);return D.value%2===0}],["false",D=>D.type==="BooleanValue"&&!D.value],["true",D=>D.type==="BooleanValue"&&D.value],["none",D=>D.type==="NullValue"],["string",D=>D.type==="StringValue"],["number",D=>D.type==="NumericValue"],["integer",D=>D.type==="NumericValue"&&Number.isInteger(D.value)],["iterable",D=>D.type==="ArrayValue"||D.type==="StringValue"],["mapping",D=>D.type==="ObjectValue"],["lower",D=>{const Z=D.value;return D.type==="StringValue"&&Z===Z.toLowerCase()}],["upper",D=>{const Z=D.value;return D.type==="StringValue"&&Z===Z.toUpperCase()}],["none",D=>D.type==="NullValue"],["defined",D=>D.type!=="UndefinedValue"],["undefined",D=>D.type==="UndefinedValue"],["equalto",(D,Z)=>D.value===Z.value],["eq",(D,Z)=>D.value===Z.value]]));this.parent=D}set(D,Z){return this.declareVariable(D,Le(Z))}declareVariable(D,Z){if(this.variables.has(D))throw new SyntaxError(`Variable already declared: ${D}`);return this.variables.set(D,Z),Z}setVariable(D,Z){return this.variables.set(D,Z),Z}resolve(D){if(this.variables.has(D))return this;if(this.parent)return this.parent.resolve(D);throw new Error(`Unknown variable: ${D}`)}lookupVariable(D){try{return this.resolve(D).variables.get(D)??new Ee}catch{return new Ee}}},Ie=class{constructor(D){re(this,"global");this.global=D??new Fe}run(D){return this.evaluate(D,this.global)}evaluateBinaryExpression(D,Z){const z=this.evaluate(D.left,Z);switch(D.operator.value){case"and":return z.__bool__().value?this.evaluate(D.right,Z):z;case"or":return z.__bool__().value?z:this.evaluate(D.right,Z)}const ee=this.evaluate(D.right,Z);switch(D.operator.value){case"==":return new ke(z.value==ee.value);case"!=":return new ke(z.value!=ee.value)}if(z instanceof Ee||ee instanceof Ee)throw new Error("Cannot perform operation on undefined values");if(z instanceof Pe||ee instanceof Pe)throw new Error("Cannot perform operation on null values");if(z instanceof we&&ee instanceof we)switch(D.operator.value){case"+":return new we(z.value+ee.value);case"-":return new we(z.value-ee.value);case"*":return new we(z.value*ee.value);case"/":return new we(z.value/ee.value);case"%":return new we(z.value%ee.value);case"<":return new ke(z.value":return new ke(z.value>ee.value);case">=":return new ke(z.value>=ee.value);case"<=":return new ke(z.value<=ee.value)}else if(z instanceof K&&ee instanceof K)switch(D.operator.value){case"+":return new K(z.value.concat(ee.value))}else if(ee instanceof K){const ce=ee.value.find(be=>be.value===z.value)!==void 0;switch(D.operator.value){case"in":return new ke(ce);case"not in":return new ke(!ce)}}if(z instanceof fe||ee instanceof fe)switch(D.operator.value){case"+":return new fe(z.value.toString()+ee.value.toString())}if(z instanceof fe&&ee instanceof fe)switch(D.operator.value){case"in":return new ke(ee.value.includes(z.value));case"not in":return new ke(!ee.value.includes(z.value))}if(z instanceof fe&&ee instanceof He)switch(D.operator.value){case"in":return new ke(ee.value.has(z.value));case"not in":return new ke(!ee.value.has(z.value))}throw new SyntaxError(`Unknown operator "${D.operator.value}" between ${z.type} and ${ee.type}`)}evaluateArguments(D,Z){const z=[],ee=new Map;for(const ce of D)if(ce.type==="KeywordArgumentExpression"){const be=ce;ee.set(be.key.value,this.evaluate(be.value,Z))}else{if(ee.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(ce,Z))}return[z,ee]}evaluateFilterExpression(D,Z){const z=this.evaluate(D.operand,Z);if(D.filter.type==="Identifier"){const ee=D.filter;if(ee.value==="tojson")return new fe(Ne(z));if(z instanceof K)switch(ee.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new we(z.value.length);case"reverse":return new K(z.value.reverse());case"sort":return new K(z.value.sort((ce,be)=>{if(ce.type!==be.type)throw new Error(`Cannot compare different types: ${ce.type} and ${be.type}`);switch(ce.type){case"NumericValue":return ce.value-be.value;case"StringValue":return ce.value.localeCompare(be.value);default:throw new Error(`Cannot compare type: ${ce.type}`)}}));case"join":return new fe(z.value.map(ce=>ce.value).join(""));default:throw new Error(`Unknown ArrayValue filter: ${ee.value}`)}else if(z instanceof fe)switch(ee.value){case"length":return new we(z.value.length);case"upper":return new fe(z.value.toUpperCase());case"lower":return new fe(z.value.toLowerCase());case"title":return new fe(ne(z.value));case"capitalize":return new fe(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new fe(z.value.trim());case"indent":return new fe(z.value.split(` +`)&&(D=D.slice(0,-1)),D=D.replace(/{#.*?#}/gs,"{##}"),Z.lstrip_blocks&&(D=D.replace(/^[ \t]*({[#%])/gm,"$1")),Z.trim_blocks&&(D=D.replace(/([#%]})\n/g,"$1")),D.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function u(D,Z={}){var ve,Re,Fe;const z=[],ee=p(D,Z);let ce=0;const be=je=>{let Qe="";for(;je(ee[ce]);){if(ee[ce]==="\\"){if(++ce,ce>=ee.length)throw new SyntaxError("Unexpected end of input");const Xe=ee[ce++],ut=d.get(Xe);if(ut===void 0)throw new SyntaxError(`Unexpected escaped character: ${Xe}`);Qe+=ut;continue}if(Qe+=ee[ce++],ce>=ee.length)throw new SyntaxError("Unexpected end of input")}return Qe};e:for(;ce0){z.push(new n(Xe,s.Text));continue}}be(Xe=>/\s/.test(Xe));const Qe=ee[ce];if(Qe==="-"||Qe==="+"){const Xe=(Re=z.at(-1))==null?void 0:Re.type;if(Xe===s.Text||Xe===void 0)throw new SyntaxError(`Unexpected character: ${Qe}`);switch(Xe){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++ce;const ut=be(a);z.push(new n(`${Qe}${ut}`,ut.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Xe,ut]of l)if(ee.slice(ce,ce+Xe.length)===Xe){z.push(new n(Xe,ut)),ce+=Xe.length;continue e}if(Qe==="'"||Qe==='"'){++ce;const Xe=be(ut=>ut!==Qe);z.push(new n(Xe,s.StringLiteral)),++ce;continue}if(a(Qe)){const Xe=be(a);z.push(new n(Xe,s.NumericLiteral));continue}if(o(Qe)){const Xe=be(o),ut=Object.hasOwn(i,Xe)?i[Xe]:s.Identifier;ut===s.In&&((Fe=z.at(-1))==null?void 0:Fe.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Xe,ut));continue}throw new SyntaxError(`Unexpected character: ${Qe}`)}return z}var h=class{constructor(){re(this,"type","Statement")}},w=class extends h{constructor(Z){super();re(this,"type","Program");this.body=Z}},f=class extends h{constructor(Z,z,ee){super();re(this,"type","If");this.test=Z,this.body=z,this.alternate=ee}},P=class extends h{constructor(Z,z,ee,ce){super();re(this,"type","For");this.loopvar=Z,this.iterable=z,this.body=ee,this.defaultBlock=ce}},A=class extends h{constructor(Z,z){super();re(this,"type","Set");this.assignee=Z,this.value=z}},b=class extends h{constructor(Z,z,ee){super();re(this,"type","Macro");this.name=Z,this.args=z,this.body=ee}},y=class extends h{constructor(){super(...arguments);re(this,"type","Expression")}},$=class extends y{constructor(Z,z,ee){super();re(this,"type","MemberExpression");this.object=Z,this.property=z,this.computed=ee}},T=class extends y{constructor(Z,z){super();re(this,"type","CallExpression");this.callee=Z,this.args=z}},g=class extends y{constructor(Z){super();re(this,"type","Identifier");this.value=Z}},M=class extends y{constructor(Z){super();re(this,"type","Literal");this.value=Z}},E=class extends M{constructor(){super(...arguments);re(this,"type","NumericLiteral")}},k=class extends M{constructor(){super(...arguments);re(this,"type","StringLiteral")}},B=class extends M{constructor(){super(...arguments);re(this,"type","BooleanLiteral")}},N=class extends M{constructor(){super(...arguments);re(this,"type","NullLiteral")}},J=class extends M{constructor(){super(...arguments);re(this,"type","ArrayLiteral")}},q=class extends M{constructor(){super(...arguments);re(this,"type","TupleLiteral")}},V=class extends M{constructor(){super(...arguments);re(this,"type","ObjectLiteral")}},Y=class extends y{constructor(Z,z,ee){super();re(this,"type","BinaryExpression");this.operator=Z,this.left=z,this.right=ee}},H=class extends y{constructor(Z,z){super();re(this,"type","FilterExpression");this.operand=Z,this.filter=z}},Q=class extends y{constructor(Z,z){super();re(this,"type","SelectExpression");this.iterable=Z,this.test=z}},ie=class extends y{constructor(Z,z,ee){super();re(this,"type","TestExpression");this.operand=Z,this.negate=z,this.test=ee}},le=class extends y{constructor(Z,z){super();re(this,"type","UnaryExpression");this.operator=Z,this.argument=z}},ae=class extends y{constructor(Z=void 0,z=void 0,ee=void 0){super();re(this,"type","SliceExpression");this.start=Z,this.stop=z,this.step=ee}},we=class extends y{constructor(Z,z){super();re(this,"type","KeywordArgumentExpression");this.key=Z,this.value=z}};function R(D){const Z=new w([]);let z=0;function ee(Be,et){const it=D[z++];if(!it||it.type!==Be)throw new Error(`Parser Error: ${et}. ${it.type} !== ${Be}.`);return it}function ce(){switch(D[z].type){case s.Text:return Re();case s.OpenStatement:return Fe();case s.OpenExpression:return je();default:throw new SyntaxError(`Unexpected token type: ${D[z].type}`)}}function be(...Be){return z+Be.length<=D.length&&Be.some((et,it)=>et!==D[z+it].type)}function ve(...Be){return z+Be.length<=D.length&&Be.every((et,it)=>et===D[z+it].type)}function Re(){return new k(ee(s.Text,"Expected text token").value)}function Fe(){ee(s.OpenStatement,"Expected opening statement token");let Be;switch(D[z].type){case s.Set:++z,Be=Qe(),ee(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,Be=Xe(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndIf,"Expected endif token"),ee(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,Be=ut(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndMacro,"Expected endmacro token"),ee(s.CloseStatement,"Expected %} token");break;case s.For:++z,Be=nr(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndFor,"Expected endfor token"),ee(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${D[z].type}`)}return Be}function je(){ee(s.OpenExpression,"Expected opening expression token");const Be=jt();return ee(s.CloseExpression,"Expected closing expression token"),Be}function Qe(){const Be=jt();if(ve(s.Equals)){++z;const et=Qe();return new A(Be,et)}return Be}function Xe(){var rr,zt,Ir,ps,hs,Er,ms,_s;const Be=jt();ee(s.CloseStatement,"Expected closing statement token");const et=[],it=[];for(;!(((rr=D[z])==null?void 0:rr.type)===s.OpenStatement&&(((zt=D[z+1])==null?void 0:zt.type)===s.ElseIf||((Ir=D[z+1])==null?void 0:Ir.type)===s.Else||((ps=D[z+1])==null?void 0:ps.type)===s.EndIf));)et.push(ce());if(((hs=D[z])==null?void 0:hs.type)===s.OpenStatement&&((Er=D[z+1])==null?void 0:Er.type)!==s.EndIf)if(++z,ve(s.ElseIf))ee(s.ElseIf,"Expected elseif token"),it.push(Xe());else for(ee(s.Else,"Expected else token"),ee(s.CloseStatement,"Expected closing statement token");!(((ms=D[z])==null?void 0:ms.type)===s.OpenStatement&&((_s=D[z+1])==null?void 0:_s.type)===s.EndIf);)it.push(ce());return new f(Be,et,it)}function ut(){const Be=mr();if(Be.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const et=qr();ee(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndMacro);)it.push(ce());return new b(Be,et,it)}function wt(Be=!1){const et=Be?mr:jt,it=[et()],rr=ve(s.Comma);for(;rr&&(++z,it.push(et()),!!ve(s.Comma)););return rr?new q(it):it[0]}function nr(){const Be=wt(!0);if(!(Be instanceof g||Be instanceof q))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Be.type} instead`);ee(s.In,"Expected `in` keyword following loop variable");const et=jt();ee(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndFor)&&be(s.OpenStatement,s.Else);)it.push(ce());const rr=[];if(ve(s.OpenStatement,s.Else))for(++z,++z,ee(s.CloseStatement,"Expected closing statement token");be(s.OpenStatement,s.EndFor);)rr.push(ce());return new P(Be,et,it,rr)}function jt(){return dr()}function dr(){const Be=ds();if(ve(s.If)){++z;const et=ds();if(ve(s.Else)){++z;const it=ds();return new f(et,[Be],[it])}else return new Q(Be,et)}return Be}function ds(){let Be=Fs();for(;ve(s.Or);){const et=D[z];++z;const it=Fs();Be=new Y(et,Be,it)}return Be}function Fs(){let Be=Dr();for(;ve(s.And);){const et=D[z];++z;const it=Dr();Be=new Y(et,Be,it)}return Be}function Dr(){let Be;for(;ve(s.Not);){const et=D[z];++z;const it=Dr();Be=new le(et,it)}return Be??cs()}function cs(){let Be=Os();for(;ve(s.ComparisonBinaryOperator)||ve(s.In)||ve(s.NotIn);){const et=D[z];++z;const it=Os();Be=new Y(et,Be,it)}return Be}function Os(){let Be=Ts();for(;ve(s.AdditiveBinaryOperator);){const et=D[z];++z;const it=Ts();Be=new Y(et,Be,it)}return Be}function jr(){const Be=xs(mr());return ve(s.OpenParen)?dt(Be):Be}function dt(Be){let et=new T(Be,qr());return et=xs(et),ve(s.OpenParen)&&(et=dt(et)),et}function qr(){ee(s.OpenParen,"Expected opening parenthesis for arguments list");const Be=Ur();return ee(s.CloseParen,"Expected closing parenthesis for arguments list"),Be}function Ur(){const Be=[];for(;!ve(s.CloseParen);){let et=jt();if(ve(s.Equals)){if(++z,!(et instanceof g))throw new SyntaxError("Expected identifier for keyword argument");const it=jt();et=new we(et,it)}Be.push(et),ve(s.Comma)&&++z}return Be}function us(){const Be=[];let et=!1;for(;!ve(s.CloseSquareBracket);)ve(s.Colon)?(Be.push(void 0),++z,et=!0):(Be.push(jt()),ve(s.Colon)&&(++z,et=!0));if(Be.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(et){if(Be.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ae(...Be)}return Be[0]}function xs(Be){for(;ve(s.Dot)||ve(s.OpenSquareBracket);){const et=D[z];++z;let it;const rr=et.type!==s.Dot;if(rr)it=us(),ee(s.CloseSquareBracket,"Expected closing square bracket");else if(it=mr(),it.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Be=new $(Be,it,rr)}return Be}function Ts(){let Be=Es();for(;ve(s.MultiplicativeBinaryOperator);){const et=D[z];++z;const it=Es();Be=new Y(et,Be,it)}return Be}function Es(){let Be=Ds();for(;ve(s.Is);){++z;const et=ve(s.Not);et&&++z;let it=mr();if(it instanceof B?it=new g(it.value.toString()):it instanceof N&&(it=new g("none")),!(it instanceof g))throw new SyntaxError("Expected identifier for the test");Be=new ie(Be,et,it)}return Be}function Ds(){let Be=jr();for(;ve(s.Pipe);){++z;let et=mr();if(!(et instanceof g))throw new SyntaxError("Expected identifier for the filter");ve(s.OpenParen)&&(et=dt(et)),Be=new H(Be,et)}return Be}function mr(){const Be=D[z];switch(Be.type){case s.NumericLiteral:return++z,new E(Number(Be.value));case s.StringLiteral:return++z,new k(Be.value);case s.BooleanLiteral:return++z,new B(Be.value.toLowerCase()==="true");case s.NullLiteral:return++z,new N(null);case s.Identifier:return++z,new g(Be.value);case s.OpenParen:{++z;const et=wt();if(D[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${D[z].type} instead`);return++z,et}case s.OpenSquareBracket:{++z;const et=[];for(;!ve(s.CloseSquareBracket);)et.push(jt()),ve(s.Comma)&&++z;return++z,new J(et)}case s.OpenCurlyBracket:{++z;const et=new Map;for(;!ve(s.CloseCurlyBracket);){const it=jt();ee(s.Colon,"Expected colon between key and value in object literal");const rr=jt();et.set(it,rr),ve(s.Comma)&&++z}return++z,new V(et)}default:throw new SyntaxError(`Unexpected token: ${Be.type}`)}}for(;z=0?(Z=(Z??(Z=0))<0?Math.max(D.length+Z,0):Math.min(Z,D.length),z=(z??(z=D.length))<0?Math.max(D.length+z,0):Math.min(z,D.length)):(Z=(Z??(Z=D.length-1))<0?Math.max(D.length+Z,-1):Math.min(Z,D.length-1),z=(z??(z=-1))<-1?Math.max(D.length+z,-1):Math.min(z,D.length-1));const be=[];for(let ve=Z;ce*veZ.toUpperCase())}var X=class{constructor(D=void 0){re(this,"type","RuntimeValue");re(this,"value");re(this,"builtins",new Map);this.value=D}__bool__(){return new ke(!!this.value)}},ye=class extends X{constructor(){super(...arguments);re(this,"type","NumericValue")}},_e=class extends X{constructor(){super(...arguments);re(this,"type","StringValue");re(this,"builtins",new Map([["upper",new pe(()=>new _e(this.value.toUpperCase()))],["lower",new pe(()=>new _e(this.value.toLowerCase()))],["strip",new pe(()=>new _e(this.value.trim()))],["title",new pe(()=>new _e(ne(this.value)))],["length",new ye(this.value.length)],["rstrip",new pe(()=>new _e(this.value.trimEnd()))],["lstrip",new pe(()=>new _e(this.value.trimStart()))],["split",new pe(Z=>{const z=Z[0]??new Pe;if(!(z instanceof _e||z instanceof Pe))throw new Error("sep argument must be a string or null");const ee=Z[1]??new ye(-1);if(!(ee instanceof ye))throw new Error("maxsplit argument must be a number");let ce=[];if(z instanceof Pe){const be=this.value.trimStart();for(const{0:ve,index:Re}of be.matchAll(/\S+/g)){if(ee.value!==-1&&ce.length>=ee.value&&Re!==void 0){ce.push(ve+be.slice(Re+ve.length));break}ce.push(ve)}}else{if(z.value==="")throw new Error("empty separator");ce=this.value.split(z.value),ee.value!==-1&&ce.length>ee.value&&ce.push(ce.splice(ee.value).join(z.value))}return new K(ce.map(be=>new _e(be)))})]]))}},ke=class extends X{constructor(){super(...arguments);re(this,"type","BooleanValue")}},He=class extends X{constructor(){super(...arguments);re(this,"type","ObjectValue");re(this,"builtins",new Map([["get",new pe(([Z,z])=>{if(!(Z instanceof _e))throw new Error(`Object key must be a string: got ${Z.type}`);return this.value.get(Z.value)??z??new Pe})],["items",new pe(()=>new K(Array.from(this.value.entries()).map(([Z,z])=>new K([new _e(Z),z]))))]]))}__bool__(){return new ke(this.value.size>0)}},Me=class extends He{constructor(){super(...arguments);re(this,"type","KeywordArgumentsValue")}},K=class extends X{constructor(){super(...arguments);re(this,"type","ArrayValue");re(this,"builtins",new Map([["length",new ye(this.value.length)]]))}__bool__(){return new ke(this.value.length>0)}},U=class extends K{constructor(){super(...arguments);re(this,"type","TupleValue")}},pe=class extends X{constructor(){super(...arguments);re(this,"type","FunctionValue")}},Pe=class extends X{constructor(){super(...arguments);re(this,"type","NullValue")}},Te=class extends X{constructor(){super(...arguments);re(this,"type","UndefinedValue")}},Ae=class{constructor(D){re(this,"variables",new Map([["namespace",new pe(D=>{if(D.length===0)return new He(new Map);if(D.length!==1||!(D[0]instanceof He))throw new Error("`namespace` expects either zero arguments or a single object argument");return D[0]})]]));re(this,"tests",new Map([["boolean",D=>D.type==="BooleanValue"],["callable",D=>D instanceof pe],["odd",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${D.type}`);return D.value%2!==0}],["even",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${D.type}`);return D.value%2===0}],["false",D=>D.type==="BooleanValue"&&!D.value],["true",D=>D.type==="BooleanValue"&&D.value],["none",D=>D.type==="NullValue"],["string",D=>D.type==="StringValue"],["number",D=>D.type==="NumericValue"],["integer",D=>D.type==="NumericValue"&&Number.isInteger(D.value)],["iterable",D=>D.type==="ArrayValue"||D.type==="StringValue"],["mapping",D=>D.type==="ObjectValue"],["lower",D=>{const Z=D.value;return D.type==="StringValue"&&Z===Z.toLowerCase()}],["upper",D=>{const Z=D.value;return D.type==="StringValue"&&Z===Z.toUpperCase()}],["none",D=>D.type==="NullValue"],["defined",D=>D.type!=="UndefinedValue"],["undefined",D=>D.type==="UndefinedValue"],["equalto",(D,Z)=>D.value===Z.value],["eq",(D,Z)=>D.value===Z.value]]));this.parent=D}set(D,Z){return this.declareVariable(D,Le(Z))}declareVariable(D,Z){if(this.variables.has(D))throw new SyntaxError(`Variable already declared: ${D}`);return this.variables.set(D,Z),Z}setVariable(D,Z){return this.variables.set(D,Z),Z}resolve(D){if(this.variables.has(D))return this;if(this.parent)return this.parent.resolve(D);throw new Error(`Unknown variable: ${D}`)}lookupVariable(D){try{return this.resolve(D).variables.get(D)??new Te}catch{return new Te}}},Ie=class{constructor(D){re(this,"global");this.global=D??new Ae}run(D){return this.evaluate(D,this.global)}evaluateBinaryExpression(D,Z){const z=this.evaluate(D.left,Z);switch(D.operator.value){case"and":return z.__bool__().value?this.evaluate(D.right,Z):z;case"or":return z.__bool__().value?z:this.evaluate(D.right,Z)}const ee=this.evaluate(D.right,Z);switch(D.operator.value){case"==":return new ke(z.value==ee.value);case"!=":return new ke(z.value!=ee.value)}if(z instanceof Te||ee instanceof Te)throw new Error("Cannot perform operation on undefined values");if(z instanceof Pe||ee instanceof Pe)throw new Error("Cannot perform operation on null values");if(z instanceof ye&&ee instanceof ye)switch(D.operator.value){case"+":return new ye(z.value+ee.value);case"-":return new ye(z.value-ee.value);case"*":return new ye(z.value*ee.value);case"/":return new ye(z.value/ee.value);case"%":return new ye(z.value%ee.value);case"<":return new ke(z.value":return new ke(z.value>ee.value);case">=":return new ke(z.value>=ee.value);case"<=":return new ke(z.value<=ee.value)}else if(z instanceof K&&ee instanceof K)switch(D.operator.value){case"+":return new K(z.value.concat(ee.value))}else if(ee instanceof K){const ce=ee.value.find(be=>be.value===z.value)!==void 0;switch(D.operator.value){case"in":return new ke(ce);case"not in":return new ke(!ce)}}if(z instanceof _e||ee instanceof _e)switch(D.operator.value){case"+":return new _e(z.value.toString()+ee.value.toString())}if(z instanceof _e&&ee instanceof _e)switch(D.operator.value){case"in":return new ke(ee.value.includes(z.value));case"not in":return new ke(!ee.value.includes(z.value))}if(z instanceof _e&&ee instanceof He)switch(D.operator.value){case"in":return new ke(ee.value.has(z.value));case"not in":return new ke(!ee.value.has(z.value))}throw new SyntaxError(`Unknown operator "${D.operator.value}" between ${z.type} and ${ee.type}`)}evaluateArguments(D,Z){const z=[],ee=new Map;for(const ce of D)if(ce.type==="KeywordArgumentExpression"){const be=ce;ee.set(be.key.value,this.evaluate(be.value,Z))}else{if(ee.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(ce,Z))}return[z,ee]}evaluateFilterExpression(D,Z){const z=this.evaluate(D.operand,Z);if(D.filter.type==="Identifier"){const ee=D.filter;if(ee.value==="tojson")return new _e(Ne(z));if(z instanceof K)switch(ee.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new ye(z.value.length);case"reverse":return new K(z.value.reverse());case"sort":return new K(z.value.sort((ce,be)=>{if(ce.type!==be.type)throw new Error(`Cannot compare different types: ${ce.type} and ${be.type}`);switch(ce.type){case"NumericValue":return ce.value-be.value;case"StringValue":return ce.value.localeCompare(be.value);default:throw new Error(`Cannot compare type: ${ce.type}`)}}));case"join":return new _e(z.value.map(ce=>ce.value).join(""));default:throw new Error(`Unknown ArrayValue filter: ${ee.value}`)}else if(z instanceof _e)switch(ee.value){case"length":return new ye(z.value.length);case"upper":return new _e(z.value.toUpperCase());case"lower":return new _e(z.value.toLowerCase());case"title":return new _e(ne(z.value));case"capitalize":return new _e(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new _e(z.value.trim());case"indent":return new _e(z.value.split(` `).map((ce,be)=>be===0||ce.length===0?ce:" "+ce).join(` -`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${ee.value}`)}else if(z instanceof we)switch(ee.value){case"abs":return new we(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${ee.value}`)}else if(z instanceof He)switch(ee.value){case"items":return new K(Array.from(z.value.entries()).map(([ce,be])=>new K([new fe(ce),be])));case"length":return new we(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ee.value}`)}throw new Error(`Cannot apply filter "${ee.value}" to type: ${z.type}`)}else if(D.filter.type==="CallExpression"){const ee=D.filter;if(ee.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ee.callee.type}`);const ce=ee.callee.value;if(ce==="tojson"){const[,be]=this.evaluateArguments(ee.args,Z),ve=be.get("indent")??new Pe;if(!(ve instanceof we||ve instanceof Pe))throw new Error("If set, indent must be a number");return new fe(Ne(z,ve.value))}else if(ce==="join"){let be;if(z instanceof fe)be=Array.from(z.value);else if(z instanceof K)be=z.value.map(Ue=>Ue.value);else throw new Error(`Cannot apply filter "${ce}" to type: ${z.type}`);const[ve,Re]=this.evaluateArguments(ee.args,Z),Ae=ve.at(0)??Re.get("separator")??new fe("");if(!(Ae instanceof fe))throw new Error("separator must be a string");return new fe(be.join(Ae.value))}if(z instanceof K){switch(ce){case"selectattr":case"rejectattr":{const be=ce==="selectattr";if(z.value.some(Xe=>!(Xe instanceof He)))throw new Error(`\`${ce}\` can only be applied to array of objects`);if(ee.args.some(Xe=>Xe.type!=="StringLiteral"))throw new Error(`arguments of \`${ce}\` must be strings`);const[ve,Re,Ae]=ee.args.map(Xe=>this.evaluate(Xe,Z));let Ue;if(Re){const Xe=Z.tests.get(Re.value);if(!Xe)throw new Error(`Unknown test: ${Re.value}`);Ue=Xe}else Ue=(...Xe)=>Xe[0].__bool__().value;const Qe=z.value.filter(Xe=>{const ct=Xe.value.get(ve.value),xt=ct?Ue(ct,Ae):!1;return be?xt:!xt});return new K(Qe)}case"map":{const[,be]=this.evaluateArguments(ee.args,Z);if(be.has("attribute")){const ve=be.get("attribute");if(!(ve instanceof fe))throw new Error("attribute must be a string");const Re=be.get("default"),Ae=z.value.map(Ue=>{if(!(Ue instanceof He))throw new Error("items in map must be an object");return Ue.value.get(ve.value)??Re??new Ee});return new K(Ae)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ce}`)}else if(z instanceof fe){switch(ce){case"indent":{const[be,ve]=this.evaluateArguments(ee.args,Z),Re=be.at(0)??ve.get("width")??new we(4);if(!(Re instanceof we))throw new Error("width must be a number");const Ae=be.at(1)??ve.get("first")??new ke(!1),Ue=be.at(2)??ve.get("blank")??new ke(!1),Qe=z.value.split(` -`),Xe=" ".repeat(Re.value),ct=Qe.map((xt,nr)=>!Ae.value&&nr===0||!Ue.value&&xt.length===0?xt:Xe+xt);return new fe(ct.join(` -`))}}throw new Error(`Unknown StringValue filter: ${ce}`)}else throw new Error(`Cannot apply filter "${ce}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${D.filter.type}`)}evaluateTestExpression(D,Z){const z=this.evaluate(D.operand,Z),ee=Z.tests.get(D.test.value);if(!ee)throw new Error(`Unknown test: ${D.test.value}`);const ce=ee(z);return new ke(D.negate?!ce:ce)}evaluateUnaryExpression(D,Z){const z=this.evaluate(D.argument,Z);switch(D.operator.value){case"not":return new ke(!z.value);default:throw new SyntaxError(`Unknown operator: ${D.operator.value}`)}}evalProgram(D,Z){return this.evaluateBlock(D.body,Z)}evaluateBlock(D,Z){let z="";for(const ee of D){const ce=this.evaluate(ee,Z);ce.type!=="NullValue"&&ce.type!=="UndefinedValue"&&(z+=ce.value)}return new fe(z)}evaluateIdentifier(D,Z){return Z.lookupVariable(D.value)}evaluateCallExpression(D,Z){const[z,ee]=this.evaluateArguments(D.args,Z);ee.size>0&&z.push(new Me(ee));const ce=this.evaluate(D.callee,Z);if(ce.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ce.type}`);return ce.value(z,Z)}evaluateSliceExpression(D,Z,z){if(!(D instanceof K||D instanceof fe))throw new Error("Slice object must be an array or string");const ee=this.evaluate(Z.start,z),ce=this.evaluate(Z.stop,z),be=this.evaluate(Z.step,z);if(!(ee instanceof we||ee instanceof Ee))throw new Error("Slice start must be numeric or undefined");if(!(ce instanceof we||ce instanceof Ee))throw new Error("Slice stop must be numeric or undefined");if(!(be instanceof we||be instanceof Ee))throw new Error("Slice step must be numeric or undefined");return D instanceof K?new K(G(D.value,ee.value,ce.value,be.value)):new fe(G(Array.from(D.value),ee.value,ce.value,be.value).join(""))}evaluateMemberExpression(D,Z){const z=this.evaluate(D.object,Z);let ee;if(D.computed){if(D.property.type==="SliceExpression")return this.evaluateSliceExpression(z,D.property,Z);ee=this.evaluate(D.property,Z)}else ee=new fe(D.property.value);let ce;if(z instanceof He){if(!(ee instanceof fe))throw new Error(`Cannot access property with non-string: got ${ee.type}`);ce=z.value.get(ee.value)??z.builtins.get(ee.value)}else if(z instanceof K||z instanceof fe)if(ee instanceof we)ce=z.value.at(ee.value),z instanceof fe&&(ce=new fe(z.value.at(ee.value)));else if(ee instanceof fe)ce=z.builtins.get(ee.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ee.type}`);else{if(!(ee instanceof fe))throw new Error(`Cannot access property with non-string: got ${ee.type}`);ce=z.builtins.get(ee.value)}return ce instanceof X?ce:new Ee}evaluateSet(D,Z){const z=this.evaluate(D.value,Z);if(D.assignee.type==="Identifier"){const ee=D.assignee.value;Z.setVariable(ee,z)}else if(D.assignee.type==="MemberExpression"){const ee=D.assignee,ce=this.evaluate(ee.object,Z);if(!(ce instanceof He))throw new Error("Cannot assign to member of non-object");if(ee.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ce.value.set(ee.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(D.assignee)}`);return new Pe}evaluateIf(D,Z){const z=this.evaluate(D.test,Z);return this.evaluateBlock(z.__bool__().value?D.body:D.alternate,Z)}evaluateFor(D,Z){const z=new Fe(Z);let ee,ce;if(D.iterable.type==="SelectExpression"){const Ue=D.iterable;ce=this.evaluate(Ue.iterable,z),ee=Ue.test}else ce=this.evaluate(D.iterable,z);if(!(ce instanceof K))throw new Error(`Expected iterable type in for loop: got ${ce.type}`);const be=[],ve=[];for(let Ue=0;Uext.setVariable(D.loopvar.value,Xe);else if(D.loopvar.type==="TupleLiteral"){const xt=D.loopvar;if(Xe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Xe.type}`);const nr=Xe;if(xt.value.length!==nr.value.length)throw new Error(`Too ${xt.value.length>nr.value.length?"few":"many"} items to unpack`);ct=jt=>{for(let dr=0;dr0?be[Ue-1]:new Ee],["nextitem",Ue{var ve;const ce=new Fe(ee);z=z.slice();let be;((ve=z.at(-1))==null?void 0:ve.type)==="KeywordArgumentsValue"&&(be=z.pop());for(let Re=0;Rethis.evaluate(z,Z)));case"TupleLiteral":return new U(D.value.map(z=>this.evaluate(z,Z)));case"ObjectLiteral":{const z=new Map;for(const[ee,ce]of D.value){const be=this.evaluate(ee,Z);if(!(be instanceof fe))throw new Error(`Object keys must be strings: got ${be.type}`);z.set(be.value,this.evaluate(ce,Z))}return new He(z)}case"Identifier":return this.evaluateIdentifier(D,Z);case"CallExpression":return this.evaluateCallExpression(D,Z);case"MemberExpression":return this.evaluateMemberExpression(D,Z);case"UnaryExpression":return this.evaluateUnaryExpression(D,Z);case"BinaryExpression":return this.evaluateBinaryExpression(D,Z);case"FilterExpression":return this.evaluateFilterExpression(D,Z);case"TestExpression":return this.evaluateTestExpression(D,Z);default:throw new SyntaxError(`Unknown node type: ${D.type}`)}}};function Le(D){switch(typeof D){case"number":return new we(D);case"string":return new fe(D);case"boolean":return new ke(D);case"undefined":return new Ee;case"object":return D===null?new Pe:Array.isArray(D)?new K(D.map(Le)):new He(new Map(Object.entries(D).map(([Z,z])=>[Z,Le(z)])));case"function":return new pe((Z,z)=>{const ee=D(...Z.map(ce=>ce.value))??null;return Le(ee)});default:throw new Error(`Cannot convert to runtime value: ${D}`)}}function Ne(D,Z,z){const ee=z??0;switch(D.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(D.value);case"ArrayValue":case"ObjectValue":{const ce=Z?" ".repeat(Z):"",be=` -`+ce.repeat(ee),ve=be+ce;if(D.type==="ArrayValue"){const Re=D.value.map(Ae=>Ne(Ae,Z,ee+1));return Z?`[${ve}${Re.join(`,${ve}`)}${be}]`:`[${Re.join(", ")}]`}else{const Re=Array.from(D.value.entries()).map(([Ae,Ue])=>{const Qe=`"${Ae}": ${Ne(Ue,Z,ee+1)}`;return Z?`${ve}${Qe}`:Qe});return Z?`{${Re.join(",")}${be}}`:`{${Re.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${D.type}`)}}var Ve=class{constructor(D){re(this,"parsed");const Z=u(D,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=N(Z)}render(D){const Z=new Fe;if(Z.set("false",!1),Z.set("true",!0),Z.set("raise_exception",ce=>{throw new Error(ce)}),Z.set("range",O),D)for(const[ce,be]of Object.entries(D))Z.set(ce,be);return new Ie(Z).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>A,deviceToExecutionProviders:()=>_,isONNXProxy:()=>S,isONNXTensor:()=>v});var i=t("./src/env.js"),n=t("?2ce3"),o=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),d=[];let p,u;const h=Symbol.for("onnxruntime");if(h in globalThis)u=globalThis[h];else if(i.apis.IS_NODE_ENV){switch(u=n??(s||(s=t.t(n,2))),process.platform){case"win32":d.push("dml");break;case"linux":process.arch==="x64"&&d.push("cuda");break}d.push("cpu"),p=["cpu"]}else u=o,i.apis.IS_WEBNN_AVAILABLE&&d.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),i.apis.IS_WEBGPU_AVAILABLE&&d.push("webgpu"),d.push("wasm"),p=["wasm"];const w=u.InferenceSession;function _(x=null){if(!x)return p;switch(x){case"auto":return d;case"gpu":return d.filter(g=>["webgpu","cuda","dml","webnn-gpu"].includes(g))}if(d.includes(x))return[l[x]??x];throw new Error(`Unsupported device: "${x}". Should be one of: ${d.join(", ")}.`)}let P=null;async function A(x,g,M){P&&await P;const E=w.create(x,g);P??(P=E);const k=await E;return k.config=M,k}function v(x){return x instanceof u.Tensor}const y=u==null?void 0:u.env;y!=null&&y.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!y.wasm.wasmPaths&&(y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${i.env.version}/dist/`),y.wasm.proxy=!1),y!=null&&y.webgpu&&(y.webgpu.powerPreference="high-performance");function S(){var x;return(x=y==null?void 0:y.wasm)==null?void 0:x.proxy}i.env.backends.onnx=y},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>o,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(d){super(),this.config=d}static async from_pretrained(d,p){const u=await(0,n.getModelJSON)(d,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(u)}}function a(l,d){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${d} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>x,center_to_corners_format:()=>u,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>h,post_process_panoptic_segmentation:()=>y,post_process_semantic_segmentation:()=>w});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var o=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function d(g,M,E=0,k=null){const B=g/M;let R=(0,n.bankers_round)(B)*M;return k!==null&&R>k&&(R=Math.floor(B)*M),RM&&O.push(ne)}else{let ne=(0,n.max)(N.data)[1];if(ne===V-1||(G=(0,n.softmax)(N.data),G[ne]we*Q[(fe+1)%2])),ie.boxes.push(X),ie.classes.push(ne),ie.scores.push(G[ne])}}Y.push(ie)}return Y}function w(g,M=null){const E=g.logits,k=E.dims[0];if(M!==null&&M.length!==k)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const B=[];for(let R=0;RQ[O]&&(Q[O]=N[O],ie[O]=ge)}const le=new Array(q.dims[0]);for(let ge=0;gege!==void 0);B.push({segmentation:H,labels:ae})}return B}function _(g,M,E,k){const B=[],R=[],J=[];for(let q=0;qE&&(B.push(Y),R.push(ie),J.push(H))}return[B,R,J]}function P(g,M,E,k=.5,B=.8){const R=[];let J=0,q=0;const V=M[E].data;for(let H=0;H=k&&++q;let Y=J>0&&q>0;return Y&&(Y=J/q>B),[Y,R]}function A(g,M,E,k,B,R=null,J=null){const[q,V]=J??g[0].dims,Y=new i.Tensor("int32",new Int32Array(q*V),[q,V]),H=[];if(J!==null)for(let ge=0;geie[G]&&(Q[G]=ge,ie[G]=O[G])}let le=0;const ae=Y.data;for(let ge=0;ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(g,M)/Math.min(g,M)}`);let R=Math.round(g/E)*E,J=Math.round(M/E)*E;if(R*J>B){const q=Math.sqrt(g*M/B);R=Math.floor(g/q/E)*E,J=Math.floor(M/q/E)*E}else if(R*JR?Y=Math.floor(R*V/B):R>B&&(V=Math.floor(B*Y/R)),await M.resize(Y,V,{resample:k}))}async crop_margin(M,E=200){const k=M.clone().grayscale(),B=(0,n.min)(k.data)[0],J=(0,n.max)(k.data)[0]-B;if(J===0)return M;const q=E/255;let V=k.width,Y=k.height,H=0,Q=0;const ie=k.data;for(let le=0;lethis.preprocess(R)));return{pixel_values:(0,i.stack)(k.map(R=>R.pixel_values),0),original_sizes:k.map(R=>R.original_size),reshaped_input_sizes:k.map(R=>R.reshaped_input_size)}}static async from_pretrained(M,E){const k=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,E);return new this(k)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(l,d){super(),this.config=l,this.components=d}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,d={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...d})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...d){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...d);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,d){const[p,u]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,d):{},Promise.all(this.classes.filter(h=>h in this).map(async h=>{const w=await this[h].from_pretrained(l,d);return[h.replace(/_class$/,""),w]})).then(Object.fromEntries)]);return new this(p,u)}}re(o,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),re(o,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>d,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js");async function n(p,u){return await(0,i.getModelJSON)(p,"config.json",!0,u)}function o(p){const u={};let h={};switch(p.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":h=o(p.text_config);break;case"moondream1":h=o(p.phi_config);break;case"musicgen":h=o(p.decoder);break;case"multi_modality":h=o(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"glm":case"helium":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _=o(p.decoder),P="num_decoder_layers"in _,A=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return P?(A.num_decoder_layers=_.num_decoder_layers,A.num_decoder_heads=_.num_decoder_heads,A.decoder_hidden_size=_.decoder_hidden_size,A.num_encoder_layers=_.num_encoder_layers,A.num_encoder_heads=_.num_encoder_heads,A.encoder_hidden_size=_.encoder_hidden_size):(A.num_layers=_.num_layers,A.num_heads=_.num_heads,A.hidden_size=_.hidden_size),A}const w={...h,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const _ in u)w[_]=p[u[_]];return w}function a(p,{prefix:u="past_key_values",batch_size:h=1}={}){const w={},_=p.normalized_config;if(_.is_encoder_decoder&&"num_encoder_heads"in _&&"num_decoder_heads"in _){const P=_.encoder_dim_kv??_.encoder_hidden_size/_.num_encoder_heads,A=_.decoder_dim_kv??_.decoder_hidden_size/_.num_decoder_heads,v=[h,_.num_encoder_heads,0,P],y=[h,_.num_decoder_heads,0,A];for(let S=0;S<_.num_decoder_layers;++S)w[`${u}.${S}.encoder.key`]=v,w[`${u}.${S}.encoder.value`]=v,w[`${u}.${S}.decoder.key`]=y,w[`${u}.${S}.decoder.value`]=y}else{const P=_.num_heads,A=_.num_layers,v=_.dim_kv??_.hidden_size/(_.num_attention_heads??P);if(_.model_type==="falcon"){const y=[h*P,0,v];for(let S=0;S{var k,B;t.r(r),t.d(r,{apis:()=>A,env:()=>M});var s=t("?569f"),i=t("?3f59"),n=t("?154a");const o="3.4.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((k=self.constructor)==null?void 0:k.name)==="DedicatedWorkerGlobalScope",d=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,u=typeof navigator<"u"&&"ml"in navigator,h=typeof process<"u",w=h&&((B=process==null?void 0:process.release)==null?void 0:B.name)==="node",_=!E(s),P=!E(i),A=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:d,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:u,IS_PROCESS_AVAILABLE:h,IS_NODE_ENV:w,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:P}),v=_&&P;let y="./";if(v){const R=Object({url:self.location.href}).url;R?y=i.dirname(i.dirname(n.fileURLToPath(R))):typeof __dirname<"u"&&(y=i.dirname(__dirname))}const S=v?i.join(y,"/.cache/"):null,x="/models/",g=v?i.join(y,x):x,M={version:o,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:g,useFS:_,useBrowserCache:d,useFSCache:_,cacheDir:S,useCustomCache:!1,customCache:null};function E(R){return Object.keys(R).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>i});var s=t("./src/utils/core.js");class i{constructor(o){re(this,"max_length",20);re(this,"max_new_tokens",null);re(this,"min_length",0);re(this,"min_new_tokens",null);re(this,"early_stopping",!1);re(this,"max_time",null);re(this,"do_sample",!1);re(this,"num_beams",1);re(this,"num_beam_groups",1);re(this,"penalty_alpha",null);re(this,"use_cache",!0);re(this,"temperature",1);re(this,"top_k",50);re(this,"top_p",1);re(this,"typical_p",1);re(this,"epsilon_cutoff",0);re(this,"eta_cutoff",0);re(this,"diversity_penalty",0);re(this,"repetition_penalty",1);re(this,"encoder_repetition_penalty",1);re(this,"length_penalty",1);re(this,"no_repeat_ngram_size",0);re(this,"bad_words_ids",null);re(this,"force_words_ids",null);re(this,"renormalize_logits",!1);re(this,"constraints",null);re(this,"forced_bos_token_id",null);re(this,"forced_eos_token_id",null);re(this,"remove_invalid_values",!1);re(this,"exponential_decay_length_penalty",null);re(this,"suppress_tokens",null);re(this,"streamer",null);re(this,"begin_suppress_tokens",null);re(this,"forced_decoder_ids",null);re(this,"guidance_scale",null);re(this,"num_return_sequences",1);re(this,"output_attentions",!1);re(this,"output_hidden_states",!1);re(this,"output_scores",!1);re(this,"return_dict_in_generate",!1);re(this,"pad_token_id",null);re(this,"bos_token_id",null);re(this,"eos_token_id",null);re(this,"encoder_no_repeat_ngram_size",0);re(this,"decoder_start_token_id",null);re(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(o,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>v,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>d,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>o,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>P,NoBadWordsLogitsProcessor:()=>A,NoRepeatNGramLogitsProcessor:()=>h,RepetitionPenaltyLogitsProcessor:()=>w,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>y,TopKLogitsWarper:()=>x,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>u});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var i=t("./src/utils/maths.js");class n extends s.Callable{_call(M,E){throw Error("`_call` should be implemented in a subclass")}}class o extends s.Callable{_call(M,E){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(M){this.processors.push(M)}extend(M){this.processors.push(...M)}_call(M,E){let k=E;for(const B of this.processors)k=B(M,k);return k}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,E){for(let k=0;k=1&&R[R.length-1]>=this.timestamp_begin,q=R.length<2||R[R.length-2]>=this.timestamp_begin;if(J&&(q?B.subarray(this.timestamp_begin).fill(-1/0):B.subarray(0,this.eos_token_id).fill(-1/0)),M[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Q=this.timestamp_begin+this.max_initial_timestamp_index;B.subarray(Q+1).fill(-1/0)}const V=(0,i.log_softmax)(B),Y=Math.log(V.subarray(this.timestamp_begin).map(Math.exp).reduce((Q,ie)=>Q+ie)),H=(0,i.max)(V.subarray(0,this.timestamp_begin))[0];Y>H&&B.subarray(0,this.timestamp_begin).fill(-1/0)}return E}}class h extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const E=M.length,k=[];for(let R=0;R1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,E){if(E.dims[0]!==2*M.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${E.dims[0]} for the logits and ${M.length} for the input ids.`);const k=M.length,B=E.slice([0,k],null),R=E.slice([k,E.dims[0]],null);for(let J=0;J1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=M,this.filter_value=E,this.min_tokens_to_keep=k}}class x extends o{constructor(M,{filter_value:E=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(M)||M<0)throw new Error(`\`top_k\` must be a positive integer, but is ${M}`);this.top_k=Math.max(M,k),this.filter_value=E}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>o});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class o extends s.Callable{constructor(u){super(),this.generation_config=u}async _call(u){return this.sample(u)}async sample(u){throw Error("sample should be implemented in subclasses.")}getLogits(u,h){let w=u.dims.at(-1),_=u.data;if(h===-1)_=_.slice(-w);else{let P=h*w;_=_.slice(P,P+w)}return _}randomSelect(u){let h=0;for(let _=0;_1)return new d(u);if(u.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${u.num_return_sequences}.`);return new a(u)}}class a extends o{async sample(u){const h=(0,n.max)(u.data)[1];return[[BigInt(h),0]]}}class l extends o{async sample(u){let h=u.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[w,_]=await(0,i.topk)(u,h),P=(0,n.softmax)(w.data);return Array.from({length:this.generation_config.num_beams},()=>{const A=this.randomSelect(P);return[_.data[A],Math.log(P[A])]})}}class d extends o{async sample(u){let h=u.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[w,_]=await(0,i.topk)(u,h),P=(0,n.softmax)(w.data);return Array.from({length:this.generation_config.num_beams},(A,v)=>[_.data[v],Math.log(P[v])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>o,StoppingCriteria:()=>i,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class i extends s.Callable{_call(p,u){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof i&&(p=[p]),this.criteria.push(...p)}_call(p,u){const h=new Array(p.length).fill(!1);for(const w of this.criteria){const _=w(p,u);for(let P=0;Pu.length>=this.max_length)}}class a extends i{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,u){return p.map(h=>{const w=h.at(-1);return this.eos_token_id.some(_=>w==_)})}}class l extends i{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,u){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>o,TextStreamer:()=>l,WhisperTextStreamer:()=>d});var s=t("./src/utils/core.js"),i=t("./src/tokenizers.js"),n=t("./src/env.js");class o{put(u){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends o{constructor(u,{skip_prompt:h=!1,callback_function:w=null,token_callback_function:_=null,skip_special_tokens:P=!0,decode_kwargs:A={},...v}={}){super(),this.tokenizer=u,this.skip_prompt=h,this.callback_function=w??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:P,...A,...v},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(u){var A;if(u.length>1)throw Error("TextStreamer only supports batch size of 1");const h=this.next_tokens_are_prompt;if(h&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const w=u[0];(A=this.token_callback_function)==null||A.call(this,w),this.token_cache=(0,s.mergeArrays)(this.token_cache,w);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let P;h||_.endsWith(` -`)?(P=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,i.is_chinese_char)(_.charCodeAt(_.length-1))?(P=_.slice(this.print_len),this.print_len+=P.length):(P=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=P.length),this.on_finalized_text(P,!1)}end(){let u;this.token_cache.length>0?(u=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):u="",this.next_tokens_are_prompt=!0,this.on_finalized_text(u,!0)}on_finalized_text(u,h){var w,_;u.length>0&&((w=this.callback_function)==null||w.call(this,u)),h&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` -`))}}class d extends l{constructor(u,{skip_prompt:h=!1,callback_function:w=null,token_callback_function:_=null,on_chunk_start:P=null,on_chunk_end:A=null,on_finalize:v=null,time_precision:y=.02,skip_special_tokens:S=!0,decode_kwargs:x={}}={}){super(u,{skip_prompt:h,skip_special_tokens:S,callback_function:w,token_callback_function:_,decode_kwargs:x}),this.timestamp_begin=u.timestamp_begin,this.on_chunk_start=P,this.on_chunk_end=A,this.on_finalize=v,this.time_precision=y,this.waiting_for_timestamp=!1}put(u){var w,_;if(u.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const h=u[0];if(h.length===1){const P=Number(h[0])-this.timestamp_begin;if(P>=0){const A=P*this.time_precision;this.waiting_for_timestamp?(w=this.on_chunk_end)==null||w.call(this,A):(_=this.on_chunk_start)==null||_.call(this,A),this.waiting_for_timestamp=!this.waiting_for_timestamp,u=[[]]}}return super.put(u)}end(){var u;super.end(),(u=this.on_finalize)==null||u.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ua,ASTModel:()=>ja,ASTPreTrainedModel:()=>Gi,AlbertForMaskedLM:()=>j,AlbertForQuestionAnswering:()=>F,AlbertForSequenceClassification:()=>ue,AlbertModel:()=>Cn,AlbertPreTrainedModel:()=>Ss,AutoModel:()=>xu,AutoModelForAudioClassification:()=>W0,AutoModelForAudioFrameClassification:()=>K0,AutoModelForAudioTextToText:()=>tb,AutoModelForCTC:()=>V0,AutoModelForCausalLM:()=>A0,AutoModelForDepthEstimation:()=>X0,AutoModelForDocumentQuestionAnswering:()=>H0,AutoModelForImageClassification:()=>L0,AutoModelForImageFeatureExtraction:()=>Z0,AutoModelForImageMatting:()=>q0,AutoModelForImageSegmentation:()=>z0,AutoModelForImageTextToText:()=>eb,AutoModelForImageToImage:()=>Q0,AutoModelForMaskGeneration:()=>U0,AutoModelForMaskedLM:()=>F0,AutoModelForNormalEstimation:()=>J0,AutoModelForObjectDetection:()=>N0,AutoModelForPoseEstimation:()=>Y0,AutoModelForQuestionAnswering:()=>O0,AutoModelForSemanticSegmentation:()=>B0,AutoModelForSeq2SeqLM:()=>S0,AutoModelForSequenceClassification:()=>P0,AutoModelForSpeechSeq2Seq:()=>$0,AutoModelForTextToSpectrogram:()=>k0,AutoModelForTextToWaveform:()=>I0,AutoModelForTokenClassification:()=>C0,AutoModelForUniversalSegmentation:()=>R0,AutoModelForVision2Seq:()=>D0,AutoModelForXVector:()=>G0,AutoModelForZeroShotObjectDetection:()=>j0,BartForConditionalGeneration:()=>Wt,BartForSequenceClassification:()=>Ot,BartModel:()=>kt,BartPretrainedModel:()=>Ct,BaseModelOutput:()=>Pe,BeitForImageClassification:()=>Sl,BeitModel:()=>Cl,BeitPreTrainedModel:()=>sa,BertForMaskedLM:()=>Ie,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Le,BertForTokenClassification:()=>Ne,BertModel:()=>Fe,BertPreTrainedModel:()=>Ee,BlenderbotForConditionalGeneration:()=>Zt,BlenderbotModel:()=>Gt,BlenderbotPreTrainedModel:()=>gs,BlenderbotSmallForConditionalGeneration:()=>ws,BlenderbotSmallModel:()=>Zr,BlenderbotSmallPreTrainedModel:()=>gr,BloomForCausalLM:()=>Bo,BloomModel:()=>zo,BloomPreTrainedModel:()=>gi,CLIPModel:()=>Zi,CLIPPreTrainedModel:()=>js,CLIPSegForImageSegmentation:()=>eo,CLIPSegModel:()=>nn,CLIPSegPreTrainedModel:()=>sn,CLIPTextModel:()=>Jc,CLIPTextModelWithProjection:()=>Ja,CLIPVisionModel:()=>Yc,CLIPVisionModelWithProjection:()=>Qn,CamembertForMaskedLM:()=>xs,CamembertForQuestionAnswering:()=>Ds,CamembertForSequenceClassification:()=>Ts,CamembertForTokenClassification:()=>Es,CamembertModel:()=>us,CamembertPreTrainedModel:()=>Ur,CausalLMOutput:()=>Fn,CausalLMOutputWithPast:()=>_x,ChineseCLIPModel:()=>rl,ChineseCLIPPreTrainedModel:()=>tl,ClapAudioModelWithProjection:()=>uM,ClapModel:()=>dM,ClapPreTrainedModel:()=>Wl,ClapTextModelWithProjection:()=>cM,CodeGenForCausalLM:()=>Vr,CodeGenModel:()=>In,CodeGenPreTrainedModel:()=>ti,CohereForCausalLM:()=>vo,CohereModel:()=>bo,CoherePreTrainedModel:()=>ci,ConvBertForMaskedLM:()=>jt,ConvBertForQuestionAnswering:()=>Fs,ConvBertForSequenceClassification:()=>dr,ConvBertForTokenClassification:()=>ds,ConvBertModel:()=>nr,ConvBertPreTrainedModel:()=>xt,ConvNextForImageClassification:()=>iy,ConvNextModel:()=>ny,ConvNextPreTrainedModel:()=>tu,ConvNextV2ForImageClassification:()=>ay,ConvNextV2Model:()=>oy,ConvNextV2PreTrainedModel:()=>ru,DPTForDepthEstimation:()=>Bt,DPTModel:()=>gt,DPTPreTrainedModel:()=>ot,DacDecoderModel:()=>ZM,DacDecoderOutput:()=>XM,DacEncoderModel:()=>YM,DacEncoderOutput:()=>QM,DacModel:()=>JM,DacPreTrainedModel:()=>Jl,DebertaForMaskedLM:()=>et,DebertaForQuestionAnswering:()=>zt,DebertaForSequenceClassification:()=>it,DebertaForTokenClassification:()=>rr,DebertaModel:()=>Be,DebertaPreTrainedModel:()=>mr,DebertaV2ForMaskedLM:()=>hs,DebertaV2ForQuestionAnswering:()=>fs,DebertaV2ForSequenceClassification:()=>Er,DebertaV2ForTokenClassification:()=>ms,DebertaV2Model:()=>ps,DebertaV2PreTrainedModel:()=>kr,DecisionTransformerModel:()=>AM,DecisionTransformerPreTrainedModel:()=>IM,DeiTForImageClassification:()=>Rl,DeiTModel:()=>Bl,DeiTPreTrainedModel:()=>la,DepthAnythingForDepthEstimation:()=>an,DepthAnythingPreTrainedModel:()=>Fr,DepthProForDepthEstimation:()=>Jw,DepthProPreTrainedModel:()=>Xw,DetrForObjectDetection:()=>kl,DetrForSegmentation:()=>na,DetrModel:()=>$l,DetrObjectDetectionOutput:()=>ia,DetrPreTrainedModel:()=>xi,DetrSegmentationOutput:()=>Il,Dinov2ForImageClassification:()=>dy,Dinov2Model:()=>ly,Dinov2PreTrainedModel:()=>su,Dinov2WithRegistersForImageClassification:()=>uy,Dinov2WithRegistersModel:()=>cy,Dinov2WithRegistersPreTrainedModel:()=>nu,DistilBertForMaskedLM:()=>Js,DistilBertForQuestionAnswering:()=>Xs,DistilBertForSequenceClassification:()=>qs,DistilBertForTokenClassification:()=>Qs,DistilBertModel:()=>Ps,DistilBertPreTrainedModel:()=>Qr,DonutSwinModel:()=>sy,DonutSwinPreTrainedModel:()=>ry,EfficientNetForImageClassification:()=>wM,EfficientNetModel:()=>gM,EfficientNetPreTrainedModel:()=>mu,ElectraForMaskedLM:()=>Os,ElectraForQuestionAnswering:()=>qr,ElectraForSequenceClassification:()=>jr,ElectraForTokenClassification:()=>dt,ElectraModel:()=>cs,ElectraPreTrainedModel:()=>Dr,EsmForMaskedLM:()=>Zs,EsmForSequenceClassification:()=>en,EsmForTokenClassification:()=>Lr,EsmModel:()=>Ys,EsmPreTrainedModel:()=>_s,ExaoneForCausalLM:()=>mt,ExaoneModel:()=>mo,ExaonePreTrainedModel:()=>Us,FalconForCausalLM:()=>lM,FalconModel:()=>aM,FalconPreTrainedModel:()=>uu,FastViTForImageClassification:()=>_l,FastViTModel:()=>fl,FastViTPreTrainedModel:()=>Yo,Florence2ForConditionalGeneration:()=>Qi,Florence2PreTrainedModel:()=>Qa,GLPNForDepthEstimation:()=>ty,GLPNModel:()=>ey,GLPNPreTrainedModel:()=>eu,GPT2LMHeadModel:()=>Yn,GPT2Model:()=>ol,GPT2PreTrainedModel:()=>to,GPTBigCodeForCausalLM:()=>co,GPTBigCodeModel:()=>ll,GPTBigCodePreTrainedModel:()=>Oe,GPTJForCausalLM:()=>kn,GPTJModel:()=>lo,GPTJPreTrainedModel:()=>ao,GPTNeoForCausalLM:()=>io,GPTNeoModel:()=>no,GPTNeoPreTrainedModel:()=>Zn,GPTNeoXForCausalLM:()=>oo,GPTNeoXModel:()=>al,GPTNeoXPreTrainedModel:()=>ei,Gemma2ForCausalLM:()=>Po,Gemma2Model:()=>Eo,Gemma2PreTrainedModel:()=>pi,GemmaForCausalLM:()=>To,GemmaModel:()=>xo,GemmaPreTrainedModel:()=>ui,GlmForCausalLM:()=>_t,GlmModel:()=>ho,GlmPreTrainedModel:()=>ii,GraniteForCausalLM:()=>Mo,GraniteModel:()=>yo,GranitePreTrainedModel:()=>di,GroundingDinoForObjectDetection:()=>hy,GroundingDinoPreTrainedModel:()=>py,GroupViTModel:()=>ml,GroupViTPreTrainedModel:()=>hl,HeliumForCausalLM:()=>ni,HeliumModel:()=>po,HeliumPreTrainedModel:()=>si,HieraForImageClassification:()=>c,HieraModel:()=>ca,HieraPreTrainedModel:()=>da,HubertForCTC:()=>Vy,HubertForSequenceClassification:()=>Wy,HubertModel:()=>Uy,HubertPreTrainedModel:()=>rx,IJepaForImageClassification:()=>Ko,IJepaModel:()=>Go,IJepaPreTrainedModel:()=>bi,Idefics3ForConditionalGeneration:()=>Hn,Idefics3PreTrainedModel:()=>Xa,ImageMattingOutput:()=>sb,JAISLMHeadModel:()=>so,JAISModel:()=>ro,JAISPreTrainedModel:()=>$n,JinaCLIPModel:()=>sl,JinaCLIPPreTrainedModel:()=>Jn,JinaCLIPTextModel:()=>nl,JinaCLIPVisionModel:()=>il,LiteWhisperForConditionalGeneration:()=>Wa,LlamaForCausalLM:()=>uo,LlamaModel:()=>ri,LlamaPreTrainedModel:()=>on,LlavaForConditionalGeneration:()=>Kn,LlavaOnevisionForConditionalGeneration:()=>Ha,LlavaPreTrainedModel:()=>Ka,LongT5ForConditionalGeneration:()=>qe,LongT5Model:()=>We,LongT5PreTrainedModel:()=>Ce,M2M100ForConditionalGeneration:()=>xy,M2M100Model:()=>vy,M2M100PreTrainedModel:()=>au,MBartForCausalLM:()=>xr,MBartForConditionalGeneration:()=>_r,MBartForSequenceClassification:()=>Yr,MBartModel:()=>vr,MBartPreTrainedModel:()=>Ut,MPNetForMaskedLM:()=>zr,MPNetForQuestionAnswering:()=>Ar,MPNetForSequenceClassification:()=>En,MPNetForTokenClassification:()=>Bs,MPNetModel:()=>Tn,MPNetPreTrainedModel:()=>Xr,MT5ForConditionalGeneration:()=>ht,MT5Model:()=>Ze,MT5PreTrainedModel:()=>Ke,MarianMTModel:()=>by,MarianModel:()=>My,MarianPreTrainedModel:()=>ou,MaskFormerForInstanceSegmentation:()=>Zw,MaskFormerModel:()=>Yw,MaskFormerPreTrainedModel:()=>Zc,MaskedLMOutput:()=>wr,MgpstrForSceneTextRecognition:()=>zM,MgpstrModelOutput:()=>DM,MgpstrPreTrainedModel:()=>LM,MimiDecoderModel:()=>qM,MimiDecoderOutput:()=>GM,MimiEncoderModel:()=>HM,MimiEncoderOutput:()=>WM,MimiModel:()=>KM,MimiPreTrainedModel:()=>Xl,MistralForCausalLM:()=>nM,MistralModel:()=>sM,MistralPreTrainedModel:()=>du,MobileBertForMaskedLM:()=>Ls,MobileBertForQuestionAnswering:()=>Ir,MobileBertForSequenceClassification:()=>zs,MobileBertModel:()=>br,MobileBertPreTrainedModel:()=>Cs,MobileLLMForCausalLM:()=>fo,MobileLLMModel:()=>ft,MobileLLMPreTrainedModel:()=>An,MobileNetV1ForImageClassification:()=>MM,MobileNetV1ForSemanticSegmentation:()=>bM,MobileNetV1Model:()=>yM,MobileNetV1PreTrainedModel:()=>Kl,MobileNetV2ForImageClassification:()=>xM,MobileNetV2ForSemanticSegmentation:()=>TM,MobileNetV2Model:()=>vM,MobileNetV2PreTrainedModel:()=>Hl,MobileNetV3ForImageClassification:()=>PM,MobileNetV3ForSemanticSegmentation:()=>CM,MobileNetV3Model:()=>EM,MobileNetV3PreTrainedModel:()=>ql,MobileNetV4ForImageClassification:()=>$M,MobileNetV4ForSemanticSegmentation:()=>kM,MobileNetV4Model:()=>SM,MobileNetV4PreTrainedModel:()=>Ql,MobileViTForImageClassification:()=>Ml,MobileViTModel:()=>yl,MobileViTPreTrainedModel:()=>Zo,MobileViTV2ForImageClassification:()=>vl,MobileViTV2Model:()=>bl,MobileViTV2PreTrainedModel:()=>ea,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>ee,ModernBertForTokenClassification:()=>ce,ModernBertModel:()=>Z,ModernBertPreTrainedModel:()=>D,Moondream1ForConditionalGeneration:()=>qa,MoonshineForConditionalGeneration:()=>Ga,MoonshineModel:()=>Xc,MoonshinePreTrainedModel:()=>Hi,MptForCausalLM:()=>No,MptModel:()=>Ro,MptPreTrainedModel:()=>wi,MultiModalityCausalLM:()=>OM,MultiModalityPreTrainedModel:()=>FM,MusicgenForCausalLM:()=>ox,MusicgenForConditionalGeneration:()=>_u,MusicgenModel:()=>ix,MusicgenPreTrainedModel:()=>fu,NomicBertModel:()=>ve,NomicBertPreTrainedModel:()=>be,OPTForCausalLM:()=>Uo,OPTModel:()=>jo,OPTPreTrainedModel:()=>yi,Olmo2ForCausalLM:()=>li,Olmo2Model:()=>wo,Olmo2PreTrainedModel:()=>ai,OlmoForCausalLM:()=>go,OlmoModel:()=>_o,OlmoPreTrainedModel:()=>oi,OpenELMForCausalLM:()=>So,OpenELMModel:()=>Co,OpenELMPreTrainedModel:()=>hi,OwlViTForObjectDetection:()=>Tl,OwlViTModel:()=>xl,OwlViTPreTrainedModel:()=>ta,Owlv2ForObjectDetection:()=>Pl,Owlv2Model:()=>El,Owlv2PreTrainedModel:()=>ra,PaliGemmaForConditionalGeneration:()=>Ji,PaliGemmaPreTrainedModel:()=>Xi,PatchTSMixerForPrediction:()=>jM,PatchTSMixerModel:()=>NM,PatchTSMixerPreTrainedModel:()=>wu,PatchTSTForPrediction:()=>RM,PatchTSTModel:()=>BM,PatchTSTPreTrainedModel:()=>gu,Phi3ForCausalLM:()=>Lo,Phi3Model:()=>Do,Phi3PreTrainedModel:()=>_i,Phi3VForCausalLM:()=>Ns,Phi3VPreTrainedModel:()=>Yi,PhiForCausalLM:()=>Oo,PhiModel:()=>Fo,PhiPreTrainedModel:()=>fi,PreTrainedModel:()=>U,PretrainedMixin:()=>It,PvtForImageClassification:()=>Xo,PvtModel:()=>Qo,PvtPreTrainedModel:()=>vi,PyAnnoteForAudioFrameClassification:()=>$y,PyAnnoteModel:()=>Sy,PyAnnotePreTrainedModel:()=>lu,QuestionAnsweringModelOutput:()=>Pr,Qwen2ForCausalLM:()=>ko,Qwen2Model:()=>$o,Qwen2PreTrainedModel:()=>mi,Qwen2VLForConditionalGeneration:()=>Ao,Qwen2VLPreTrainedModel:()=>Io,RTDetrForObjectDetection:()=>Fl,RTDetrModel:()=>Al,RTDetrObjectDetectionOutput:()=>Ol,RTDetrPreTrainedModel:()=>oa,ResNetForImageClassification:()=>C,ResNetModel:()=>b,ResNetPreTrainedModel:()=>m,RoFormerForMaskedLM:()=>Ue,RoFormerForQuestionAnswering:()=>ct,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>Xe,RoFormerModel:()=>Ae,RoFormerPreTrainedModel:()=>Re,RobertaForMaskedLM:()=>Rt,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Jt,RobertaForTokenClassification:()=>qt,RobertaModel:()=>ur,RobertaPreTrainedModel:()=>Ht,SamImageSegmentationOutput:()=>yy,SamModel:()=>wy,SamPreTrainedModel:()=>gy,SapiensForDepthEstimation:()=>qw,SapiensForNormalEstimation:()=>Qw,SapiensForSemanticSegmentation:()=>Hw,SapiensPreTrainedModel:()=>Nl,SegformerForImageClassification:()=>hM,SegformerForSemanticSegmentation:()=>mM,SegformerModel:()=>nx,SegformerPreTrainedModel:()=>Gl,Seq2SeqLMOutput:()=>fx,SequenceClassifierOutput:()=>Mt,SiglipModel:()=>Ya,SiglipPreTrainedModel:()=>Xn,SiglipTextModel:()=>Za,SiglipVisionModel:()=>el,SmolVLMForConditionalGeneration:()=>qn,SpeechT5ForSpeechToText:()=>Yy,SpeechT5ForTextToSpeech:()=>Zy,SpeechT5HifiGan:()=>eM,SpeechT5Model:()=>sx,SpeechT5PreTrainedModel:()=>Vl,SqueezeBertForMaskedLM:()=>fr,SqueezeBertForQuestionAnswering:()=>Pn,SqueezeBertForSequenceClassification:()=>Rs,SqueezeBertModel:()=>cr,SqueezeBertPreTrainedModel:()=>Jr,StableLmForCausalLM:()=>_M,StableLmModel:()=>fM,StableLmPreTrainedModel:()=>hu,Starcoder2ForCausalLM:()=>oM,Starcoder2Model:()=>iM,Starcoder2PreTrainedModel:()=>cu,StyleTextToSpeech2Model:()=>Jy,StyleTextToSpeech2PreTrainedModel:()=>Xy,Swin2SRForImageSuperResolution:()=>Ye,Swin2SRModel:()=>ze,Swin2SRPreTrainedModel:()=>Te,SwinForImageClassification:()=>se,SwinForSemanticSegmentation:()=>ye,SwinModel:()=>W,SwinPreTrainedModel:()=>I,T5ForConditionalGeneration:()=>he,T5Model:()=>de,T5PreTrainedModel:()=>te,TableTransformerForObjectDetection:()=>Ll,TableTransformerModel:()=>Dl,TableTransformerObjectDetectionOutput:()=>zl,TableTransformerPreTrainedModel:()=>aa,TokenClassifierOutput:()=>pr,TrOCRForCausalLM:()=>rM,TrOCRPreTrainedModel:()=>tM,UltravoxModel:()=>VM,UltravoxPreTrainedModel:()=>UM,UniSpeechForCTC:()=>Fy,UniSpeechForSequenceClassification:()=>Oy,UniSpeechModel:()=>Ay,UniSpeechPreTrainedModel:()=>jl,UniSpeechSatForAudioFrameClassification:()=>By,UniSpeechSatForCTC:()=>Ly,UniSpeechSatForSequenceClassification:()=>zy,UniSpeechSatModel:()=>Dy,UniSpeechSatPreTrainedModel:()=>ua,ViTForImageClassification:()=>Wo,ViTMAEModel:()=>cl,ViTMAEPreTrainedModel:()=>dl,ViTMSNForImageClassification:()=>pl,ViTMSNModel:()=>ul,ViTMSNPreTrainedModel:()=>Jo,ViTModel:()=>Vo,ViTPreTrainedModel:()=>Mi,VisionEncoderDecoderModel:()=>qi,VitMatteForImageMatting:()=>wl,VitMattePreTrainedModel:()=>gl,VitPoseForPoseEstimation:()=>qo,VitPosePreTrainedModel:()=>Ho,VitsModel:()=>pu,VitsModelOutput:()=>nb,VitsPreTrainedModel:()=>pM,Wav2Vec2BertForCTC:()=>Ny,Wav2Vec2BertForSequenceClassification:()=>jy,Wav2Vec2BertModel:()=>Ry,Wav2Vec2BertPreTrainedModel:()=>Ul,Wav2Vec2ForAudioFrameClassification:()=>Cy,Wav2Vec2ForCTC:()=>Ey,Wav2Vec2ForSequenceClassification:()=>Py,Wav2Vec2Model:()=>Ty,Wav2Vec2PreTrainedModel:()=>ln,WavLMForAudioFrameClassification:()=>Qy,WavLMForCTC:()=>Ky,WavLMForSequenceClassification:()=>Hy,WavLMForXVector:()=>qy,WavLMModel:()=>Gy,WavLMPreTrainedModel:()=>Ti,WeSpeakerResNetModel:()=>Iy,WeSpeakerResNetPreTrainedModel:()=>ky,WhisperForConditionalGeneration:()=>Ki,WhisperModel:()=>Va,WhisperPreTrainedModel:()=>Gn,XLMForQuestionAnswering:()=>za,XLMForSequenceClassification:()=>La,XLMForTokenClassification:()=>Vi,XLMModel:()=>tn,XLMPreTrainedModel:()=>ir,XLMRobertaForMaskedLM:()=>Ra,XLMRobertaForQuestionAnswering:()=>Wi,XLMRobertaForSequenceClassification:()=>Sn,XLMRobertaForTokenClassification:()=>Na,XLMRobertaModel:()=>Ba,XLMRobertaPreTrainedModel:()=>ys,XLMWithLMHeadModel:()=>rn,XVectorOutput:()=>rb,YolosForObjectDetection:()=>fy,YolosModel:()=>my,YolosObjectDetectionOutput:()=>_y,YolosPreTrainedModel:()=>iu});var s=t("./src/configs.js"),i=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),o=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),d=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),u=t("./src/generation/configuration_utils.js"),h=t("./src/utils/tensor.js"),w=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),P=t("./src/generation/stopping_criteria.js"),A=t("./src/generation/logits_sampler.js"),v=t("./src/env.js"),y=t("./src/models/whisper/generation_whisper.js"),S=t("./src/models/whisper/common_whisper.js");const x={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},g=new Map,M=new Map,E=new Map;async function k(T,$,L){var yr;const oe=((yr=L.config)==null?void 0:yr["transformers.js_config"])??{};let _e=L.device??oe.device;_e&&typeof _e!="string"&&(_e.hasOwnProperty($)?_e=_e[$]:(console.warn(`device not specified for "${$}". Using the default device.`),_e=null));const me=_e??(v.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,i.deviceToExecutionProviders)(me);let De=L.dtype??oe.dtype;if(typeof De!="string"&&(De&&De.hasOwnProperty($)?De=De[$]:(De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${$}". Using the default dtype (${De}) for this device (${me}).`))),De===n.DATA_TYPES.auto){let Pt=oe.dtype;typeof Pt!="string"&&(Pt=Pt[$]),Pt&&Pt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Pt)?De=Pt:De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32}const Ge=De;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ge)){if(Ge===n.DATA_TYPES.fp16&&me==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${me}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ge}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const Je=oe.kv_cache_dtype?typeof oe.kv_cache_dtype=="string"?oe.kv_cache_dtype:oe.kv_cache_dtype[Ge]??"float32":void 0;if(Je&&!["float32","float16"].includes(Je))throw new Error(`Invalid kv_cache_dtype: ${Je}. Should be one of: float32, float16`);const lt={dtype:Ge,kv_cache_dtype:Je},wt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Ge],st=`${$}${wt}.onnx`,Et=`${L.subfolder??""}/${st}`,at={...L.session_options};at.executionProviders??(at.executionProviders=Se);const bt=oe.free_dimension_overrides;bt?at.freeDimensionOverrides??(at.freeDimensionOverrides=bt):me.startsWith("webnn")&&!at.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const ut=(0,l.getModelFile)(T,Et,!0,L,v.apis.IS_NODE_ENV),Tt=L.use_external_data_format??oe.use_external_data_format;let Lt=[];if(Tt){let Pt;typeof Tt=="object"?Tt.hasOwnProperty(st)?Pt=Tt[st]:Tt.hasOwnProperty($)?Pt=Tt[$]:Pt=!1:Pt=Tt;const Nt=+Pt;if(Nt>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Nt}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let tr=0;tr{const Cr=await(0,l.getModelFile)(T,Wr,!0,L,v.apis.IS_NODE_ENV);dn(Cr instanceof Uint8Array?{path:sr,data:Cr}:sr)}))}}else at.externalData!==void 0&&(Lt=at.externalData.map(async Pt=>{if(typeof Pt.data=="string"){const Nt=await(0,l.getModelFile)(T,Pt.data,!0,L);return{...Pt,data:Nt}}return Pt}));if(Lt.length>0){const Pt=await Promise.all(Lt);v.apis.IS_NODE_ENV||(at.externalData=Pt)}if(me==="webgpu"){const Pt=(0,s.getKeyValueShapes)(L.config,{prefix:"present"});if(Object.keys(Pt).length>0&&!(0,i.isONNXProxy)()){const Nt={};for(const tr in Pt)Nt[tr]="gpu-buffer";at.preferredOutputLocation=Nt}}return{buffer_or_path:await ut,session_options:at,session_config:lt}}async function B(T,$,L){return Object.fromEntries(await Promise.all(Object.keys($).map(async oe=>{const{buffer_or_path:_e,session_options:me,session_config:Se}=await k(T,$[oe],L),De=await(0,i.createInferenceSession)(_e,me,Se);return[oe,De]})))}async function R(T,$,L){return Object.fromEntries(await Promise.all(Object.keys($).map(async oe=>{const _e=await(0,l.getModelJSON)(T,$[oe],!1,L);return[oe,_e]})))}function J(T,$){const L=Object.create(null),oe=[];for(const Se of T.inputNames){const De=$[Se];if(!(De instanceof h.Tensor)){oe.push(Se);continue}L[Se]=(0,i.isONNXProxy)()?De.clone():De}if(oe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${oe.join(", ")}.`);const _e=Object.keys($).length,me=T.inputNames.length;if(_e>me){let Se=Object.keys($).filter(De=>!T.inputNames.includes(De));console.warn(`WARNING: Too many inputs were provided (${_e} > ${me}). The following inputs will be ignored: "${Se.join(", ")}".`)}return L}async function q(T,$){const L=J(T,$);try{const oe=Object.fromEntries(Object.entries(L).map(([me,Se])=>[me,Se.ort_tensor]));let _e=await T.run(oe);return _e=V(_e),_e}catch(oe){const _e=Object.fromEntries(Object.entries(L).map(([me,{type:Se,dims:De,data:Ge}])=>[me,{type:Se,dims:De,data:Ge}]));throw console.error(`An error occurred during model execution: "${oe}".`),console.error("Inputs given to model:",_e),oe}}function V(T){for(let $ in T)(0,i.isONNXTensor)(T[$])?T[$]=new h.Tensor(T[$]):typeof T[$]=="object"&&V(T[$]);return T}function Y(T){if(T instanceof h.Tensor)return T;if(T.length===0)throw Error("items must be non-empty");if(Array.isArray(T[0])){if(T.some($=>$.length!==T[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new h.Tensor("int64",BigInt64Array.from(T.flat().map($=>BigInt($))),[T.length,T[0].length])}else return new h.Tensor("int64",BigInt64Array.from(T.map($=>BigInt($))),[1,T.length])}function H(T){return new h.Tensor("bool",[T],[1])}async function Q(T,$){let{encoder_outputs:L,input_ids:oe,decoder_input_ids:_e,...me}=$;if(!L){const De=(0,a.pick)($,T.sessions.model.inputNames);L=(await ie(T,De)).last_hidden_state}return me.input_ids=_e,me.encoder_hidden_states=L,T.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(me.encoder_attention_mask=$.attention_mask),await ae(T,me,!0)}async function ie(T,$){const L=T.sessions.model,oe=(0,a.pick)($,L.inputNames);if(L.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds){if(!$.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");oe.inputs_embeds=await T.encode_text({input_ids:$.input_ids})}if(L.inputNames.includes("token_type_ids")&&!oe.token_type_ids){if(!oe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");oe.token_type_ids=(0,h.zeros_like)(oe.input_ids)}if(L.inputNames.includes("pixel_mask")&&!oe.pixel_mask){if(!oe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const _e=oe.pixel_values.dims;oe.pixel_mask=(0,h.ones)([_e[0],_e[2],_e[3]])}return await q(L,oe)}async function le(T,$){const L=await T.encode($);return await T.decode(L)}async function ae(T,$,L=!1){const oe=T.sessions[L?"decoder_model_merged":"model"],{past_key_values:_e,...me}=$;if(oe.inputNames.includes("use_cache_branch")&&(me.use_cache_branch=H(!!_e)),oe.inputNames.includes("position_ids")&&me.attention_mask&&!me.position_ids){const De=T.config.model_type==="paligemma"?1:0;me.position_ids=fe(me,_e,De)}T.addPastKeyValues(me,_e);const Se=(0,a.pick)(me,oe.inputNames);return await q(oe,Se)}function ge({modality_token_id:T,inputs_embeds:$,modality_features:L,input_ids:oe,attention_mask:_e}){const me=oe.tolist().map(Je=>Je.reduce((lt,wt,st)=>(wt==T&<.push(st),lt),[])),Se=me.reduce((Je,lt)=>Je+lt.length,0),De=L.dims[0];if(Se!==De)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${De}`);let Ge=0;for(let Je=0;Jeme.dims[1])){if(_eDe==T.config.image_token_index)){const De=T.config.num_image_tokens;if(!De)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ge=me.dims[1]-(_e-De);L.input_ids=me.slice(null,[-Ge,null]),L.attention_mask=(0,h.ones)([1,_e+Ge])}}}return L}function He(T,$,L,oe){return L.past_key_values&&($=$.map(_e=>[_e.at(-1)])),{...L,decoder_input_ids:Y($)}}function Me(T,...$){return T.config.is_encoder_decoder?He(T,...$):ke(T,...$)}function K(T,$,L,oe){const _e=!!L.past_key_values;return oe.guidance_scale!==null&&oe.guidance_scale>1&&(_e?L.input_ids=(0,h.cat)([L.input_ids,L.input_ids],0):(L.input_ids=(0,h.cat)([L.input_ids,(0,h.full_like)(L.input_ids,BigInt(oe.pad_token_id))],0),L.attention_mask=(0,h.cat)([L.attention_mask,(0,h.full_like)(L.attention_mask,0n)],0))),(_e||!L.pixel_values)&&(L.pixel_values=(0,h.full)([0,0,3,384,384],1)),_e&&(L.images_seq_mask=new h.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),L.images_emb_mask=new h.Tensor("bool",new Array(0).fill(!1),[1,1,0])),L}class U extends o.Callable{constructor(L,oe,_e){super();re(this,"main_input_name","input_ids");re(this,"forward_params",["input_ids","attention_mask"]);this.config=L,this.sessions=oe,this.configs=_e;const me=E.get(this.constructor),Se=g.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Se){case x.DecoderOnly:this.can_generate=!0,this._forward=ae,this._prepare_inputs_for_generation=ke;break;case x.Seq2Seq:case x.Vision2Seq:case x.Musicgen:this.can_generate=!0,this._forward=Q,this._prepare_inputs_for_generation=He;break;case x.EncoderDecoder:this._forward=Q;break;case x.ImageTextToText:this.can_generate=!0,this._forward=X,this._prepare_inputs_for_generation=Me;break;case x.AudioTextToText:this.can_generate=!0,this._forward=ne,this._prepare_inputs_for_generation=Me;break;case x.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Me;break;case x.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=K;break;case x.AutoEncoder:this._forward=le;break;default:this._forward=ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var oe;const L=[];for(const _e of Object.values(this.sessions))(oe=_e==null?void 0:_e.handler)!=null&&oe.dispose&&L.push(_e.handler.dispose());return await Promise.all(L)}static async from_pretrained(L,{progress_callback:oe=null,config:_e=null,cache_dir:me=null,local_files_only:Se=!1,revision:De="main",model_file_name:Ge=null,subfolder:Je="onnx",device:lt=null,dtype:wt=null,use_external_data_format:st=null,session_options:Et={}}={}){let at={progress_callback:oe,config:_e,cache_dir:me,local_files_only:Se,revision:De,model_file_name:Ge,subfolder:Je,device:lt,dtype:wt,use_external_data_format:st,session_options:Et};const bt=E.get(this),ut=g.get(bt);_e=at.config=await s.AutoConfig.from_pretrained(L,at);let Tt;if(ut===x.DecoderOnly)Tt=await Promise.all([B(L,{model:at.model_file_name??"model"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.Seq2Seq||ut===x.Vision2Seq)Tt=await Promise.all([B(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.MaskGeneration)Tt=await Promise.all([B(L,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},at)]);else if(ut===x.EncoderDecoder)Tt=await Promise.all([B(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at)]);else if(ut===x.ImageTextToText){const Lt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};_e.is_encoder_decoder&&(Lt.model="encoder_model"),Tt=await Promise.all([B(L,Lt,at),R(L,{generation_config:"generation_config.json"},at)])}else if(ut===x.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};Tt=await Promise.all([B(L,Lt,at),R(L,{generation_config:"generation_config.json"},at)])}else if(ut===x.Musicgen)Tt=await Promise.all([B(L,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.MultiModality)Tt=await Promise.all([B(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.Phi3V)Tt=await Promise.all([B(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.AutoEncoder)Tt=await Promise.all([B(L,{encoder_model:"encoder_model",decoder_model:"decoder_model"},at)]);else{if(ut!==x.EncoderOnly){const Lt=bt??(_e==null?void 0:_e.model_type);Lt!=="custom"&&console.warn(`Model type for '${Lt}' not found, assuming encoder-only architecture. Please report this at ${d.GITHUB_ISSUE_URL}.`)}Tt=await Promise.all([B(L,{model:at.model_file_name??"model"},at)])}return new this(_e,...Tt)}async _call(L){return await this.forward(L)}async forward(L){return await this._forward(this,L)}get generation_config(){var L;return((L=this.configs)==null?void 0:L.generation_config)??null}_get_logits_warper(L){const oe=new p.LogitsProcessorList;return L.temperature!==null&&L.temperature!==1&&oe.push(new p.TemperatureLogitsWarper(L.temperature)),L.top_k!==null&&L.top_k!==0&&oe.push(new p.TopKLogitsWarper(L.top_k)),L.top_p!==null&&L.top_p<1&&oe.push(new p.TopPLogitsWarper(L.top_p)),oe}_get_logits_processor(L,oe,_e=null){const me=new p.LogitsProcessorList;if(L.repetition_penalty!==null&&L.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(L.repetition_penalty)),L.no_repeat_ngram_size!==null&&L.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(L.no_repeat_ngram_size)),L.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(L.bad_words_ids,L.eos_token_id)),L.min_length!==null&&L.eos_token_id!==null&&L.min_length>0&&me.push(new p.MinLengthLogitsProcessor(L.min_length,L.eos_token_id)),L.min_new_tokens!==null&&L.eos_token_id!==null&&L.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(oe,L.min_new_tokens,L.eos_token_id)),L.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(L.forced_bos_token_id)),L.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(L.max_length,L.forced_eos_token_id)),L.begin_suppress_tokens!==null){const Se=oe>1||L.forced_bos_token_id===null?oe:oe+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se))}return L.guidance_scale!==null&&L.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(L.guidance_scale)),_e!==null&&me.extend(_e),me}_prepare_generation_config(L,oe,_e=u.GenerationConfig){const me={...this.config};for(const De of["decoder","generator","text_config"])De in me&&Object.assign(me,me[De]);const Se=new _e(me);return Object.assign(Se,this.generation_config??{}),L&&Object.assign(Se,L),oe&&Object.assign(Se,(0,a.pick)(oe,Object.getOwnPropertyNames(Se))),Se}_get_stopping_criteria(L,oe=null){const _e=new P.StoppingCriteriaList;return L.max_length!==null&&_e.push(new P.MaxLengthCriteria(L.max_length,this.config.max_position_embeddings??null)),L.eos_token_id!==null&&_e.push(new P.EosTokenCriteria(L.eos_token_id)),oe&&_e.extend(oe),_e}_validate_model_class(){if(!this.can_generate){const L=[bu,vu,Mu,yu],oe=E.get(this.constructor),_e=new Set,me=this.config.model_type;for(const De of L){const Ge=De.get(me);Ge&&_e.add(Ge[0])}let Se=`The current model class (${oe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw _e.size>0&&(Se+=` Please use the following class instead: ${[..._e].join(", ")}`),Error(Se)}}prepare_inputs_for_generation(...L){return this._prepare_inputs_for_generation(this,...L)}_update_model_kwargs_for_generation({generated_input_ids:L,outputs:oe,model_inputs:_e,is_encoder_decoder:me}){return _e.past_key_values=this.getPastKeyValues(oe,_e.past_key_values),_e.input_ids=new h.Tensor("int64",L.flat(),[L.length,1]),me||(_e.attention_mask=(0,h.cat)([_e.attention_mask,(0,h.ones)([_e.attention_mask.dims[0],1])],1)),_e.position_ids=null,_e}_prepare_model_inputs({inputs:L,bos_token_id:oe,model_kwargs:_e}){const me=(0,a.pick)(_e,this.forward_params),Se=this.main_input_name;if(Se in me){if(L)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[Se]=L;return{inputs_tensor:me[Se],model_inputs:me,model_input_name:Se}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:L,model_inputs:oe,model_input_name:_e,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:De,pixel_values:Ge,attention_mask:Je,...lt}=oe,wt=await this._prepare_inputs_embeds(oe);oe={...lt,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Se}=await ie(this,oe);if(me.guidance_scale!==null&&me.guidance_scale>1)Se=(0,h.cat)([Se,(0,h.full_like)(Se,0)],0),"attention_mask"in oe&&(oe.attention_mask=(0,h.cat)([oe.attention_mask,(0,h.zeros_like)(oe.attention_mask)],0));else if(oe.decoder_input_ids){const De=Y(oe.decoder_input_ids).dims[0];if(De!==Se.dims[0]){if(Se.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Se.dims[0]}) than the decoder inputs (${De}).`);Se=(0,h.cat)(Array.from({length:De},()=>Se),0)}}return oe.encoder_outputs=Se,oe}_prepare_decoder_input_ids_for_generation({batch_size:L,model_input_name:oe,model_kwargs:_e,decoder_start_token_id:me,bos_token_id:Se,generation_config:De}){let{decoder_input_ids:Ge,...Je}=_e;if(!(Ge instanceof h.Tensor)){if(Ge)Array.isArray(Ge[0])||(Ge=Array.from({length:L},()=>Ge));else if(me??(me=Se),this.config.model_type==="musicgen")Ge=Array.from({length:L*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==L)throw new Error(`\`decoder_start_token_id\` expcted to have length ${L} but got ${me.length}`);Ge=me}else Ge=Array.from({length:L},()=>[me]);Ge=Y(Ge)}return _e.decoder_attention_mask=(0,h.ones_like)(Ge),{input_ids:Ge,model_inputs:Je}}async generate({inputs:L=null,generation_config:oe=null,logits_processor:_e=null,stopping_criteria:me=null,streamer:Se=null,...De}){this._validate_model_class(),oe=this._prepare_generation_config(oe,De);let{inputs_tensor:Ge,model_inputs:Je,model_input_name:lt}=this._prepare_model_inputs({inputs:L,model_kwargs:De});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Je||(Je=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ge,model_inputs:Je,model_input_name:lt,generation_config:oe})));let st;wt?{input_ids:st,model_inputs:Je}=this._prepare_decoder_input_ids_for_generation({batch_size:Je[lt].dims.at(0),model_input_name:lt,model_kwargs:Je,decoder_start_token_id:oe.decoder_start_token_id,bos_token_id:oe.bos_token_id,generation_config:oe}):st=Je[lt];let Et=st.dims.at(-1);oe.max_new_tokens!==null&&(oe.max_length=Et+oe.max_new_tokens);const at=this._get_logits_processor(oe,Et,_e),bt=this._get_stopping_criteria(oe,me),ut=Je[lt].dims.at(0),Tt=A.LogitsSampler.getSampler(oe),Lt=new Array(ut).fill(0),Qt=st.tolist();Se&&Se.put(Qt);let yr,Pt={};for(;;){if(Je=this.prepare_inputs_for_generation(Qt,Je,oe),yr=await this.forward(Je),oe.output_attentions&&oe.return_dict_in_generate){const Cr=this.getAttentions(yr);for(const $s in Cr)$s in Pt||(Pt[$s]=[]),Pt[$s].push(Cr[$s])}const sr=yr.logits.slice(null,-1,null),Wr=at(Qt,sr),dn=[];for(let Cr=0;CrCr))break;Je=this._update_model_kwargs_for_generation({generated_input_ids:dn,outputs:yr,model_inputs:Je,is_encoder_decoder:wt})}Se&&Se.end();const Nt=this.getPastKeyValues(yr,Je.past_key_values,!0),tr=new h.Tensor("int64",Qt.flat(),[Qt.length,Qt[0].length]);if(oe.return_dict_in_generate)return{sequences:tr,past_key_values:Nt,...Pt};for(const sr of Object.values(yr))sr.location==="gpu-buffer"&&sr.dispose();return tr}getPastKeyValues(L,oe,_e=!1){const me=Object.create(null);for(const Se in L)if(Se.startsWith("present")){const De=Se.replace("present","past_key_values"),Ge=Se.includes("encoder");if(Ge&&oe?me[De]=oe[De]:me[De]=L[Se],oe&&(!Ge||_e)){const Je=oe[De];Je.location==="gpu-buffer"&&Je.dispose()}}return me}getAttentions(L){const oe={};for(const _e of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in L)me.startsWith(_e)&&(_e in oe||(oe[_e]=[]),oe[_e].push(L[me]));return oe}addPastKeyValues(L,oe){var _e,me,Se;if(oe)Object.assign(L,oe);else{const De=this.sessions.decoder_model_merged??this.sessions.model,Ge=((_e=De==null?void 0:De.config)==null?void 0:_e.kv_cache_dtype)??"float32",Je=Ge==="float16"?new h.DataTypeMap.float16:[],lt=((Se=(me=L[this.main_input_name]??L.attention_mask)==null?void 0:me.dims)==null?void 0:Se[0])??1,wt=(0,s.getKeyValueShapes)(this.config,{batch_size:lt});for(const st in wt)L[st]=new h.Tensor(Ge,Je,wt[st])}}async encode_image({pixel_values:L}){const oe=(await q(this.sessions.vision_encoder,{pixel_values:L})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${oe.dims[1]}).`),this.config.num_image_tokens=oe.dims[1]),oe}async encode_text({input_ids:L}){return(await q(this.sessions.embed_tokens,{input_ids:L})).inputs_embeds}async encode_audio({audio_values:L}){return(await q(this.sessions.audio_encoder,{audio_values:L})).audio_features}}class pe{}class Pe extends pe{constructor({last_hidden_state:$,hidden_states:L=null,attentions:oe=null}){super(),this.last_hidden_state=$,this.hidden_states=L,this.attentions=oe}}class Ee extends U{}class Fe extends Ee{}class Ie extends Ee{async _call($){return new wr(await super._call($))}}class Le extends Ee{async _call($){return new Mt(await super._call($))}}class Ne extends Ee{async _call($){return new pr(await super._call($))}}class Ve extends Ee{async _call($){return new Pr(await super._call($))}}class D extends U{}class Z extends D{}class z extends D{async _call($){return new wr(await super._call($))}}class ee extends D{async _call($){return new Mt(await super._call($))}}class ce extends D{async _call($){return new pr(await super._call($))}}class be extends U{}class ve extends be{}class Re extends U{}class Ae extends Re{}class Ue extends Re{async _call($){return new wr(await super._call($))}}class Qe extends Re{async _call($){return new Mt(await super._call($))}}class Xe extends Re{async _call($){return new pr(await super._call($))}}class ct extends Re{async _call($){return new Pr(await super._call($))}}class xt extends U{}class nr extends xt{}class jt extends xt{async _call($){return new wr(await super._call($))}}class dr extends xt{async _call($){return new Mt(await super._call($))}}class ds extends xt{async _call($){return new pr(await super._call($))}}class Fs extends xt{async _call($){return new Pr(await super._call($))}}class Dr extends U{}class cs extends Dr{}class Os extends Dr{async _call($){return new wr(await super._call($))}}class jr extends Dr{async _call($){return new Mt(await super._call($))}}class dt extends Dr{async _call($){return new pr(await super._call($))}}class qr extends Dr{async _call($){return new Pr(await super._call($))}}class Ur extends U{}class us extends Ur{}class xs extends Ur{async _call($){return new wr(await super._call($))}}class Ts extends Ur{async _call($){return new Mt(await super._call($))}}class Es extends Ur{async _call($){return new pr(await super._call($))}}class Ds extends Ur{async _call($){return new Pr(await super._call($))}}class mr extends U{}class Be extends mr{}class et extends mr{async _call($){return new wr(await super._call($))}}class it extends mr{async _call($){return new Mt(await super._call($))}}class rr extends mr{async _call($){return new pr(await super._call($))}}class zt extends mr{async _call($){return new Pr(await super._call($))}}class kr extends U{}class ps extends kr{}class hs extends kr{async _call($){return new wr(await super._call($))}}class Er extends kr{async _call($){return new Mt(await super._call($))}}class ms extends kr{async _call($){return new pr(await super._call($))}}class fs extends kr{async _call($){return new Pr(await super._call($))}}class Qr extends U{}class Ps extends Qr{}class qs extends Qr{async _call($){return new Mt(await super._call($))}}class Qs extends Qr{async _call($){return new pr(await super._call($))}}class Xs extends Qr{async _call($){return new Pr(await super._call($))}}class Js extends Qr{async _call($){return new wr(await super._call($))}}class _s extends U{}class Ys extends _s{}class Zs extends _s{async _call($){return new wr(await super._call($))}}class en extends _s{async _call($){return new Mt(await super._call($))}}class Lr extends _s{async _call($){return new pr(await super._call($))}}class Cs extends U{}class br extends Cs{}class Ls extends Cs{async _call($){return new wr(await super._call($))}}class zs extends Cs{async _call($){return new Mt(await super._call($))}}class Ir extends Cs{async _call($){return new Pr(await super._call($))}}class Xr extends U{}class Tn extends Xr{}class zr extends Xr{async _call($){return new wr(await super._call($))}}class En extends Xr{async _call($){return new Mt(await super._call($))}}class Bs extends Xr{async _call($){return new pr(await super._call($))}}class Ar extends Xr{async _call($){return new Pr(await super._call($))}}class Jr extends U{}class cr extends Jr{}class fr extends Jr{async _call($){return new wr(await super._call($))}}class Rs extends Jr{async _call($){return new Mt(await super._call($))}}class Pn extends Jr{async _call($){return new Pr(await super._call($))}}class Ss extends U{}class Cn extends Ss{}class ue extends Ss{async _call($){return new Mt(await super._call($))}}class F extends Ss{async _call($){return new Pr(await super._call($))}}class j extends Ss{async _call($){return new wr(await super._call($))}}class te extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class de extends te{}class he extends te{}class Ce extends U{}class We extends Ce{}class qe extends Ce{}class Ke extends U{}class Ze extends Ke{}class ht extends Ke{}class Ct extends U{}class kt extends Ct{}class Wt extends Ct{}class Ot extends Ct{async _call($){return new Mt(await super._call($))}}class Ut extends U{}class vr extends Ut{}class _r extends Ut{}class Yr extends Ut{async _call($){return new Mt(await super._call($))}}class xr extends Ut{}class gs extends U{}class Gt extends gs{}class Zt extends gs{}class gr extends U{}class Zr extends gr{}class ws extends gr{}class Ht extends U{}class ur extends Ht{}class Rt extends Ht{async _call($){return new wr(await super._call($))}}class Jt extends Ht{async _call($){return new Mt(await super._call($))}}class qt extends Ht{async _call($){return new pr(await super._call($))}}class er extends Ht{async _call($){return new Pr(await super._call($))}}class ir extends U{}class tn extends ir{}class rn extends ir{async _call($){return new wr(await super._call($))}}class La extends ir{async _call($){return new Mt(await super._call($))}}class Vi extends ir{async _call($){return new pr(await super._call($))}}class za extends ir{async _call($){return new Pr(await super._call($))}}class ys extends U{}class Ba extends ys{}class Ra extends ys{async _call($){return new wr(await super._call($))}}class Sn extends ys{async _call($){return new Mt(await super._call($))}}class Na extends ys{async _call($){return new pr(await super._call($))}}class Wi extends ys{async _call($){return new Pr(await super._call($))}}class Gi extends U{}class ja extends Gi{}class Ua extends Gi{}class Gn extends U{constructor(){super(...arguments);re(this,"requires_attention_mask",!1);re(this,"main_input_name","input_features");re(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Va extends Gn{}class Ki extends Gn{_prepare_generation_config($,L){return super._prepare_generation_config($,L,y.WhisperGenerationConfig)}_retrieve_init_tokens($){const L=[$.decoder_start_token_id];let oe=$.language;const _e=$.task;if($.is_multilingual){oe||(console.warn("No language specified - defaulting to English (en)."),oe="en");const Se=`<|${(0,S.whisper_language_to_code)(oe)}|>`;L.push($.lang_to_id[Se]),L.push($.task_to_id[_e??"transcribe"])}else if(oe||_e)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!$.return_timestamps&&$.no_timestamps_token_id&&L.at(-1)!==$.no_timestamps_token_id?L.push($.no_timestamps_token_id):$.return_timestamps&&L.at(-1)===$.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),L.pop()),L.filter(me=>me!=null)}async generate({inputs:$=null,generation_config:L=null,logits_processor:oe=null,stopping_criteria:_e=null,...me}){L=this._prepare_generation_config(L,me);const Se=me.decoder_input_ids??this._retrieve_init_tokens(L);if(L.return_timestamps&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.WhisperTimeStampLogitsProcessor(L,Se))),L.begin_suppress_tokens&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se.length))),L.return_token_timestamps){if(!L.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");L.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),L.output_attentions=!0,L.return_dict_in_generate=!0}const De=await super.generate({inputs:$,generation_config:L,logits_processor:oe,decoder_input_ids:Se,...me});return L.return_token_timestamps&&(De.token_timestamps=this._extract_token_timestamps(De,L.alignment_heads,L.num_frames)),De}_extract_token_timestamps($,L,oe=null,_e=.02){if(!$.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");oe==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let me=this.config.median_filter_width;me===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),me=7);const Se=$.cross_attentions,De=Array.from({length:this.config.decoder_layers},(bt,ut)=>(0,h.cat)(Se.map(Tt=>Tt[ut]),2)),Ge=(0,h.stack)(L.map(([bt,ut])=>{if(bt>=De.length)throw new Error(`Layer index ${bt} is out of bounds for cross attentions (length ${De.length}).`);return oe?De[bt].slice(null,ut,null,[0,oe]):De[bt].slice(null,ut)})).transpose(1,0,2,3),[Je,lt]=(0,h.std_mean)(Ge,-2,0,!0),wt=Ge.clone();for(let bt=0;btTt[tr+1]-Tt[tr]),yr=(0,a.mergeArrays)([1],Qt).map(Nt=>!!Nt),Pt=[];for(let Nt=0;Ntst.findIndex(Et=>Et==me)),Ge=De.every(st=>st===-1),Je=De.every(st=>st!==-1);if(!Ge&&!Je)throw new Error("Every input should contain either 0 or 1 image token.");if(Ge)return{inputs_embeds:$,attention_mask:_e};const lt=[],wt=[];for(let st=0;stArray.from({length:$.dims[0]},Qt=>Array.from({length:$.dims[1]},yr=>1))),at=L?L.tolist():[],bt=oe?oe.tolist():[];let ut=0,Tt=0;for(let Lt=0;Ltst[Lt][or]==1),Pt=Qt.reduce((Kt,or,cn)=>(or==Ge&&Kt.push(cn),Kt),[]).map(Kt=>Qt[Kt+1]),Nt=Pt.filter(Kt=>Kt==Se).length,tr=Pt.filter(Kt=>Kt==De).length;let sr=[],Wr=0,dn=Nt,Yl=tr;for(let Kt=0;KtMs>Wr&&Dn==Se),cn=Qt.findIndex((Dn,Ms)=>Ms>Wr&&Dn==De),On=dn>0&&or!==-1?or:Qt.length+1,Pi=Yl>0&&cn!==-1?cn:Qt.length+1;let rd,Eu,Pu,Cu;On0?(0,_.max)(sr.at(-1))[0]+1:0;sr.push(Array.from({length:3*$u},(Dn,Ms)=>ib+Ms%$u));const ku=$u+ib,nd=gx*Su*sd,wx=Array.from({length:nd},(Dn,Ms)=>ku+Math.floor(Ms/(Su*sd))),yx=Array.from({length:nd},(Dn,Ms)=>ku+Math.floor(Ms/sd)%Su),Mx=Array.from({length:nd},(Dn,Ms)=>ku+Ms%sd);sr.push([wx,yx,Mx].flat()),Wr=rd+nd}if(Wr0?(0,_.max)(sr.at(-1))[0]+1:0,or=Qt.length-Wr;sr.push(Array.from({length:3*or},(cn,On)=>Kt+On%or))}const Cr=sr.reduce((Kt,or)=>Kt+or.length,0),$s=new Array(Cr);let Tu=0;for(let Kt=0;Kt<3;++Kt)for(let or=0;orwt[ut%wt.length]),at=Array.from({length:st[0]},(bt,ut)=>(0,_.max)(wt.subarray(st[1]*ut,st[1]*(ut+1)))[0]+1n+BigInt(st[1]));return[new h.Tensor("int64",Et,[3,...st]),new h.Tensor("int64",at,[at.length,1])]}else{const[wt,st]=$.dims,Et=BigInt64Array.from({length:3*wt*st},(at,bt)=>BigInt(Math.floor(bt%st/wt)));return[new h.Tensor("int64",Et,[3,...$.dims]),(0,h.zeros)([wt,1])]}}async encode_image({pixel_values:$,image_grid_thw:L}){return(await q(this.sessions.vision_encoder,{pixel_values:$,grid_thw:L})).image_features}_merge_input_ids_with_image_features($){return N({image_token_id:this.config.image_token_id,...$})}prepare_inputs_for_generation($,L,oe){if(L.attention_mask&&!L.position_ids)if(!L.past_key_values)[L.position_ids,L.rope_deltas]=this.get_rope_index(L.input_ids,L.image_grid_thw,L.video_grid_thw,L.attention_mask);else{L.pixel_values=null;const _e=BigInt(Object.values(L.past_key_values)[0].dims.at(-2)),me=L.rope_deltas.map(Se=>_e+Se);L.position_ids=(0,h.stack)([me,me,me],0)}return L}}class fi extends U{}class Fo extends fi{}class Oo extends fi{}class _i extends U{}class Do extends _i{}class Lo extends _i{}class gi extends U{}class zo extends gi{}class Bo extends gi{}class wi extends U{}class Ro extends wi{}class No extends wi{}class yi extends U{}class jo extends yi{}class Uo extends yi{}class Mi extends U{}class Vo extends Mi{}class Wo extends Mi{async _call($){return new Mt(await super._call($))}}class bi extends U{}class Go extends bi{}class Ko extends bi{async _call($){return new Mt(await super._call($))}}class Ho extends U{}class qo extends Ho{}class vi extends U{}class Qo extends vi{}class Xo extends vi{async _call($){return new Mt(await super._call($))}}class dl extends U{}class cl extends dl{}class Jo extends U{}class ul extends Jo{}class pl extends Jo{async _call($){return new Mt(await super._call($))}}class hl extends U{}class ml extends hl{}class Yo extends U{}class fl extends Yo{}class _l extends Yo{async _call($){return new Mt(await super._call($))}}class gl extends U{}class wl extends gl{async _call($){return new sb(await super._call($))}}class Zo extends U{}class yl extends Zo{}class Ml extends Zo{async _call($){return new Mt(await super._call($))}}class ea extends U{}class bl extends ea{}class vl extends ea{async _call($){return new Mt(await super._call($))}}class ta extends U{}class xl extends ta{}class Tl extends ta{}class ra extends U{}class El extends ra{}class Pl extends ra{}class sa extends U{}class Cl extends sa{}class Sl extends sa{async _call($){return new Mt(await super._call($))}}class xi extends U{}class $l extends xi{}class kl extends xi{async _call($){return new ia(await super._call($))}}class na extends xi{async _call($){return new Il(await super._call($))}}class ia extends pe{constructor({logits:$,pred_boxes:L}){super(),this.logits=$,this.pred_boxes=L}}class Il extends pe{constructor({logits:$,pred_boxes:L,pred_masks:oe}){super(),this.logits=$,this.pred_boxes=L,this.pred_masks=oe}}class oa extends U{}class Al extends oa{}class Fl extends oa{async _call($){return new Ol(await super._call($))}}class Ol extends pe{constructor({logits:$,pred_boxes:L}){super(),this.logits=$,this.pred_boxes=L}}class aa extends U{}class Dl extends aa{}class Ll extends aa{async _call($){return new zl(await super._call($))}}class zl extends ia{}class la extends U{}class Bl extends la{}class Rl extends la{async _call($){return new Mt(await super._call($))}}class da extends U{}class ca extends da{}class c extends da{async _call($){return new Mt(await super._call($))}}class m extends U{}class b extends m{}class C extends m{async _call($){return new Mt(await super._call($))}}class I extends U{}class W extends I{}class se extends I{async _call($){return new Mt(await super._call($))}}class ye extends I{}class Te extends U{}class ze extends Te{}class Ye extends Te{}class ot extends U{}class gt extends ot{}class Bt extends ot{}class Fr extends U{}class an extends Fr{}class Nl extends U{}class Hw extends Nl{}class qw extends Nl{}class Qw extends Nl{}class Xw extends U{}class Jw extends Xw{}class Zc extends U{}class Yw extends Zc{}class Zw extends Zc{}class eu extends U{}class ey extends eu{}class ty extends eu{}class ry extends U{}class sy extends ry{}class tu extends U{}class ny extends tu{}class iy extends tu{async _call($){return new Mt(await super._call($))}}class ru extends U{}class oy extends ru{}class ay extends ru{async _call($){return new Mt(await super._call($))}}class su extends U{}class ly extends su{}class dy extends su{async _call($){return new Mt(await super._call($))}}class nu extends U{}class cy extends nu{}class uy extends nu{async _call($){return new Mt(await super._call($))}}class py extends U{}class hy extends py{}class iu extends U{}class my extends iu{}class fy extends iu{async _call($){return new _y(await super._call($))}}class _y extends pe{constructor({logits:$,pred_boxes:L}){super(),this.logits=$,this.pred_boxes=L}}class gy extends U{}class wy extends gy{async get_image_embeddings({pixel_values:$}){return await ie(this,{pixel_values:$})}async forward($){if((!$.image_embeddings||!$.image_positional_embeddings)&&($={...$,...await this.get_image_embeddings($)}),!$.input_labels&&$.input_points){const oe=$.input_points.dims.slice(0,-1),_e=oe.reduce((me,Se)=>me*Se,1);$.input_labels=new h.Tensor("int64",new BigInt64Array(_e).fill(1n),oe)}const L={image_embeddings:$.image_embeddings,image_positional_embeddings:$.image_positional_embeddings};return $.input_points&&(L.input_points=$.input_points),$.input_labels&&(L.input_labels=$.input_labels),$.input_boxes&&(L.input_boxes=$.input_boxes),await q(this.sessions.prompt_encoder_mask_decoder,L)}async _call($){return new yy(await super._call($))}}class yy extends pe{constructor({iou_scores:$,pred_masks:L}){super(),this.iou_scores=$,this.pred_masks=L}}class ou extends U{}class My extends ou{}class by extends ou{}class au extends U{}class vy extends au{}class xy extends au{}class ln extends U{}class Ty extends ln{}class Ey extends ln{async _call($){return new Fn(await super._call($))}}class Py extends ln{async _call($){return new Mt(await super._call($))}}class Cy extends ln{async _call($){return new pr(await super._call($))}}class lu extends U{}class Sy extends lu{}class $y extends lu{async _call($){return new pr(await super._call($))}}class ky extends U{}class Iy extends ky{}class jl extends U{}class Ay extends jl{}class Fy extends jl{async _call($){return new Fn(await super._call($))}}class Oy extends jl{async _call($){return new Mt(await super._call($))}}class ua extends U{}class Dy extends ua{}class Ly extends ua{async _call($){return new Fn(await super._call($))}}class zy extends ua{async _call($){return new Mt(await super._call($))}}class By extends ua{async _call($){return new pr(await super._call($))}}class Ul extends U{}class Ry extends Ul{}class Ny extends Ul{async _call($){return new Fn(await super._call($))}}class jy extends Ul{async _call($){return new Mt(await super._call($))}}class rx extends U{}class Uy extends ln{}class Vy extends ln{async _call($){return new Fn(await super._call($))}}class Wy extends ln{async _call($){return new Mt(await super._call($))}}class Ti extends U{}class Gy extends Ti{}class Ky extends Ti{async _call($){return new Fn(await super._call($))}}class Hy extends Ti{async _call($){return new Mt(await super._call($))}}class qy extends Ti{async _call($){return new rb(await super._call($))}}class Qy extends Ti{async _call($){return new pr(await super._call($))}}class Xy extends U{}class Jy extends Xy{}class Vl extends U{}class sx extends Vl{}class Yy extends Vl{}class Zy extends Vl{async generate_speech($,L,{threshold:oe=.5,minlenratio:_e=0,maxlenratio:me=20,vocoder:Se=null}={}){const De={input_ids:$},{encoder_outputs:Ge,encoder_attention_mask:Je}=await ie(this,De),lt=Ge.dims[1]/this.config.reduction_factor,wt=Math.floor(lt*me),st=Math.floor(lt*_e),Et=this.config.num_mel_bins;let at=[],bt=null,ut=null,Tt=0;for(;;){++Tt;const yr=H(!!ut);let Pt;ut?Pt=ut.output_sequence_out:Pt=new h.Tensor("float32",new Float32Array(Et),[1,1,Et]);let Nt={use_cache_branch:yr,output_sequence:Pt,encoder_attention_mask:Je,speaker_embeddings:L,encoder_hidden_states:Ge};this.addPastKeyValues(Nt,bt),ut=await q(this.sessions.decoder_model_merged,Nt),bt=this.getPastKeyValues(ut,bt);const{prob:tr,spectrum:sr}=ut;if(at.push(sr),Tt>=st&&(Array.from(tr.data).filter(Wr=>Wr>=oe).length>0||Tt>=wt))break}const Lt=(0,h.cat)(at),{waveform:Qt}=await q(Se.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Qt}}}class eM extends U{constructor(){super(...arguments);re(this,"main_input_name","spectrogram")}}class tM extends U{}class rM extends tM{}class du extends U{}class sM extends du{}class nM extends du{}class cu extends U{}class iM extends cu{}class oM extends cu{}class uu extends U{}class aM extends uu{}class lM extends uu{}class Wl extends U{}class dM extends Wl{}class cM extends Wl{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"text_model"})}}class uM extends Wl{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"audio_model"})}}class pM extends U{}class pu extends pM{async _call($){return new nb(await super._call($))}}class Gl extends U{}class nx extends Gl{}class hM extends Gl{}class mM extends Gl{}class hu extends U{}class fM extends hu{}class _M extends hu{}class mu extends U{}class gM extends mu{}class wM extends mu{async _call($){return new Mt(await super._call($))}}class fu extends U{}class ix extends fu{}class ox extends fu{}class _u extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(L){const[oe,_e]=L.dims,me=this.config.decoder.num_codebooks,Se=_e-me;let De=0;for(let lt=0;lt0&&Et<=Se&&(L.data[De++]=L.data[lt])}const Ge=Math.floor(oe/me),Je=De/(Ge*me);return new h.Tensor(L.type,L.data.slice(0,De),[Ge,me,Je])}prepare_inputs_for_generation(L,oe,_e){let me=structuredClone(L);for(let De=0;De=Ge&&(me[De][Ge]=BigInt(this.config.decoder.pad_token_id));return _e.guidance_scale!==null&&_e.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,oe,_e)}async generate(L){const oe=await super.generate(L),_e=this._apply_and_filter_by_delay_pattern_mask(oe).unsqueeze_(0),{audio_values:me}=await q(this.sessions.encodec_decode,{audio_codes:_e});return me}}class Kl extends U{}class yM extends Kl{}class MM extends Kl{async _call($){return new Mt(await super._call($))}}class bM extends Kl{}class Hl extends U{}class vM extends Hl{}class xM extends Hl{async _call($){return new Mt(await super._call($))}}class TM extends Hl{}class ql extends U{}class EM extends ql{}class PM extends ql{async _call($){return new Mt(await super._call($))}}class CM extends ql{}class Ql extends U{}class SM extends Ql{}class $M extends Ql{async _call($){return new Mt(await super._call($))}}class kM extends Ql{}class IM extends U{}class AM extends IM{}class FM extends U{}class OM extends FM{constructor(...L){super(...L);re(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(L){const oe=this._generation_mode??"text";let _e;if(oe==="text"||!L.past_key_values){const Je=this.sessions.prepare_inputs_embeds,lt=(0,a.pick)(L,Je.inputNames);_e=await q(Je,lt)}else{const Je=this.sessions.gen_img_embeds,lt=(0,a.pick)({image_ids:L.input_ids},Je.inputNames);_e=await q(Je,lt)}const me={...L,..._e},Se=await ae(this,me),De=this.sessions[oe==="text"?"lm_head":"gen_head"];if(!De)throw new Error(`Unable to find "${De}" generation head`);const Ge=await q(De,(0,a.pick)(Se,De.inputNames));return{..._e,...Se,...Ge}}async generate(L){return this._generation_mode="text",super.generate(L)}async generate_images(L){this._generation_mode="image";const oe=(L.inputs??L[this.main_input_name]).dims[1],me=(await super.generate(L)).slice(null,[oe,null]),Se=this.sessions.image_decode,{decoded_image:De}=await q(Se,{generated_tokens:me}),Ge=De.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Je=[];for(const lt of Ge){const wt=w.RawImage.fromTensor(lt);Je.push(wt)}return Je}}class DM extends pe{constructor({char_logits:$,bpe_logits:L,wp_logits:oe}){super(),this.char_logits=$,this.bpe_logits=L,this.wp_logits=oe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class LM extends U{}class zM extends LM{async _call($){return new DM(await super._call($))}}class gu extends U{}class BM extends gu{}class RM extends gu{}class wu extends U{}class NM extends wu{}class jM extends wu{}class UM extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class VM extends UM{_merge_input_ids_with_audio_features($){const L=$.audio_features.dims.at(-1),oe=$.audio_features.view(-1,L);return O({audio_token_id:this.config.ignore_index,...$,audio_features:oe})}}class Xl extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class WM extends pe{constructor({audio_codes:$}){super(),this.audio_codes=$}}class GM extends pe{constructor({audio_values:$}){super(),this.audio_values=$}}class KM extends Xl{async encode($){return new WM(await q(this.sessions.encoder_model,$))}async decode($){return new GM(await q(this.sessions.decoder_model,$))}}class HM extends Xl{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class qM extends Xl{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class Jl extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class QM extends pe{constructor({audio_codes:$}){super(),this.audio_codes=$}}class XM extends pe{constructor({audio_values:$}){super(),this.audio_values=$}}class JM extends Jl{async encode($){return new QM(await q(this.sessions.encoder_model,$))}async decode($){return new XM(await q(this.sessions.decoder_model,$))}}class YM extends Jl{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class ZM extends Jl{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class It{static async from_pretrained($,{progress_callback:L=null,config:oe=null,cache_dir:_e=null,local_files_only:me=!1,revision:Se="main",model_file_name:De=null,subfolder:Ge="onnx",device:Je=null,dtype:lt=null,use_external_data_format:wt=null,session_options:st={}}={}){const Et={progress_callback:L,config:oe,cache_dir:_e,local_files_only:me,revision:Se,model_file_name:De,subfolder:Ge,device:Je,dtype:lt,use_external_data_format:wt,session_options:st};if(Et.config=await s.AutoConfig.from_pretrained($,Et),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const at=Et.config.model_type;for(const bt of this.MODEL_CLASS_MAPPINGS){let ut=bt.get(at);if(!ut){for(const Tt of bt.values())if(Tt[0]===at){ut=Tt;break}if(!ut)continue}return await ut[1].from_pretrained($,Et)}if(this.BASE_IF_FAIL)return E0.has(at)||console.warn(`Unknown model class "${at}", attempting to construct from base class.`),await U.from_pretrained($,Et);throw Error(`Unsupported model type: ${at}`)}}re(It,"MODEL_CLASS_MAPPINGS",null),re(It,"BASE_IF_FAIL",!1);const ax=new Map([["bert",["BertModel",Fe]],["modernbert",["ModernBertModel",Z]],["nomic_bert",["NomicBertModel",ve]],["roformer",["RoFormerModel",Ae]],["electra",["ElectraModel",cs]],["esm",["EsmModel",Ys]],["convbert",["ConvBertModel",nr]],["camembert",["CamembertModel",us]],["deberta",["DebertaModel",Be]],["deberta-v2",["DebertaV2Model",ps]],["mpnet",["MPNetModel",Tn]],["albert",["AlbertModel",Cn]],["distilbert",["DistilBertModel",Ps]],["roberta",["RobertaModel",ur]],["xlm",["XLMModel",tn]],["xlm-roberta",["XLMRobertaModel",Ba]],["clap",["ClapModel",dM]],["clip",["CLIPModel",Zi]],["clipseg",["CLIPSegModel",nn]],["chinese_clip",["ChineseCLIPModel",rl]],["siglip",["SiglipModel",Ya]],["jina_clip",["JinaCLIPModel",sl]],["mobilebert",["MobileBertModel",br]],["squeezebert",["SqueezeBertModel",cr]],["wav2vec2",["Wav2Vec2Model",Ty]],["wav2vec2-bert",["Wav2Vec2BertModel",Ry]],["unispeech",["UniSpeechModel",Ay]],["unispeech-sat",["UniSpeechSatModel",Dy]],["hubert",["HubertModel",Uy]],["wavlm",["WavLMModel",Gy]],["audio-spectrogram-transformer",["ASTModel",ja]],["vits",["VitsModel",pu]],["pyannote",["PyAnnoteModel",Sy]],["wespeaker-resnet",["WeSpeakerResNetModel",Iy]],["detr",["DetrModel",$l]],["rt_detr",["RTDetrModel",Al]],["table-transformer",["TableTransformerModel",Dl]],["vit",["ViTModel",Vo]],["ijepa",["IJepaModel",Go]],["pvt",["PvtModel",Qo]],["vit_msn",["ViTMSNModel",ul]],["vit_mae",["ViTMAEModel",cl]],["groupvit",["GroupViTModel",ml]],["fastvit",["FastViTModel",fl]],["mobilevit",["MobileViTModel",yl]],["mobilevitv2",["MobileViTV2Model",bl]],["owlvit",["OwlViTModel",xl]],["owlv2",["Owlv2Model",El]],["beit",["BeitModel",Cl]],["deit",["DeiTModel",Bl]],["hiera",["HieraModel",ca]],["convnext",["ConvNextModel",ny]],["convnextv2",["ConvNextV2Model",oy]],["dinov2",["Dinov2Model",ly]],["dinov2_with_registers",["Dinov2WithRegistersModel",cy]],["resnet",["ResNetModel",b]],["swin",["SwinModel",W]],["swin2sr",["Swin2SRModel",ze]],["donut-swin",["DonutSwinModel",sy]],["yolos",["YolosModel",my]],["dpt",["DPTModel",gt]],["glpn",["GLPNModel",ey]],["hifigan",["SpeechT5HifiGan",eM]],["efficientnet",["EfficientNetModel",gM]],["decision_transformer",["DecisionTransformerModel",AM]],["patchtst",["PatchTSTForPrediction",BM]],["patchtsmixer",["PatchTSMixerForPrediction",NM]],["mobilenet_v1",["MobileNetV1Model",yM]],["mobilenet_v2",["MobileNetV2Model",vM]],["mobilenet_v3",["MobileNetV3Model",EM]],["mobilenet_v4",["MobileNetV4Model",SM]],["maskformer",["MaskFormerModel",Yw]],["mgp-str",["MgpstrForSceneTextRecognition",zM]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Jy]]]),lx=new Map([["t5",["T5Model",de]],["longt5",["LongT5Model",We]],["mt5",["MT5Model",Ze]],["bart",["BartModel",kt]],["mbart",["MBartModel",vr]],["marian",["MarianModel",My]],["whisper",["WhisperModel",Va]],["m2m_100",["M2M100Model",vy]],["blenderbot",["BlenderbotModel",Gt]],["blenderbot-small",["BlenderbotSmallModel",Zr]]]),dx=new Map([["mimi",["MimiModel",KM]],["dac",["DacModel",JM]]]),cx=new Map([["bloom",["BloomModel",zo]],["jais",["JAISModel",ro]],["gpt2",["GPT2Model",ol]],["gptj",["GPTJModel",lo]],["gpt_bigcode",["GPTBigCodeModel",ll]],["gpt_neo",["GPTNeoModel",no]],["gpt_neox",["GPTNeoXModel",al]],["codegen",["CodeGenModel",In]],["llama",["LlamaModel",ri]],["exaone",["ExaoneModel",mo]],["olmo",["OlmoModel",_o]],["olmo2",["Olmo2Model",wo]],["mobilellm",["MobileLLMModel",ft]],["granite",["GraniteModel",yo]],["cohere",["CohereModel",bo]],["gemma",["GemmaModel",xo]],["gemma2",["Gemma2Model",Eo]],["helium",["HeliumModel",po]],["glm",["GlmModel",ho]],["openelm",["OpenELMModel",Co]],["qwen2",["Qwen2Model",$o]],["phi",["PhiModel",Fo]],["phi3",["Phi3Model",Do]],["mpt",["MptModel",Ro]],["opt",["OPTModel",jo]],["mistral",["MistralModel",sM]],["starcoder2",["Starcoder2Model",iM]],["falcon",["FalconModel",aM]],["stablelm",["StableLmModel",fM]]]),yu=new Map([["speecht5",["SpeechT5ForSpeechToText",Yy]],["whisper",["WhisperForConditionalGeneration",Ki]],["lite-whisper",["LiteWhisperForConditionalGeneration",Wa]],["moonshine",["MoonshineForConditionalGeneration",Ga]]]),e0=new Map([["speecht5",["SpeechT5ForTextToSpeech",Zy]]]),t0=new Map([["vits",["VitsModel",pu]],["musicgen",["MusicgenForConditionalGeneration",_u]]]),r0=new Map([["bert",["BertForSequenceClassification",Le]],["modernbert",["ModernBertForSequenceClassification",ee]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",jr]],["esm",["EsmForSequenceClassification",en]],["convbert",["ConvBertForSequenceClassification",dr]],["camembert",["CamembertForSequenceClassification",Ts]],["deberta",["DebertaForSequenceClassification",it]],["deberta-v2",["DebertaV2ForSequenceClassification",Er]],["mpnet",["MPNetForSequenceClassification",En]],["albert",["AlbertForSequenceClassification",ue]],["distilbert",["DistilBertForSequenceClassification",qs]],["roberta",["RobertaForSequenceClassification",Jt]],["xlm",["XLMForSequenceClassification",La]],["xlm-roberta",["XLMRobertaForSequenceClassification",Sn]],["bart",["BartForSequenceClassification",Ot]],["mbart",["MBartForSequenceClassification",Yr]],["mobilebert",["MobileBertForSequenceClassification",zs]],["squeezebert",["SqueezeBertForSequenceClassification",Rs]]]),s0=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",ce]],["roformer",["RoFormerForTokenClassification",Xe]],["electra",["ElectraForTokenClassification",dt]],["esm",["EsmForTokenClassification",Lr]],["convbert",["ConvBertForTokenClassification",ds]],["camembert",["CamembertForTokenClassification",Es]],["deberta",["DebertaForTokenClassification",rr]],["deberta-v2",["DebertaV2ForTokenClassification",ms]],["mpnet",["MPNetForTokenClassification",Bs]],["distilbert",["DistilBertForTokenClassification",Qs]],["roberta",["RobertaForTokenClassification",qt]],["xlm",["XLMForTokenClassification",Vi]],["xlm-roberta",["XLMRobertaForTokenClassification",Na]]]),Mu=new Map([["t5",["T5ForConditionalGeneration",he]],["longt5",["LongT5ForConditionalGeneration",qe]],["mt5",["MT5ForConditionalGeneration",ht]],["bart",["BartForConditionalGeneration",Wt]],["mbart",["MBartForConditionalGeneration",_r]],["marian",["MarianMTModel",by]],["m2m_100",["M2M100ForConditionalGeneration",xy]],["blenderbot",["BlenderbotForConditionalGeneration",Zt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ws]]]),bu=new Map([["bloom",["BloomForCausalLM",Bo]],["gpt2",["GPT2LMHeadModel",Yn]],["jais",["JAISLMHeadModel",so]],["gptj",["GPTJForCausalLM",kn]],["gpt_bigcode",["GPTBigCodeForCausalLM",co]],["gpt_neo",["GPTNeoForCausalLM",io]],["gpt_neox",["GPTNeoXForCausalLM",oo]],["codegen",["CodeGenForCausalLM",Vr]],["llama",["LlamaForCausalLM",uo]],["exaone",["ExaoneForCausalLM",mt]],["olmo",["OlmoForCausalLM",go]],["olmo2",["Olmo2ForCausalLM",li]],["mobilellm",["MobileLLMForCausalLM",fo]],["granite",["GraniteForCausalLM",Mo]],["cohere",["CohereForCausalLM",vo]],["gemma",["GemmaForCausalLM",To]],["gemma2",["Gemma2ForCausalLM",Po]],["helium",["HeliumForCausalLM",ni]],["glm",["GlmForCausalLM",_t]],["openelm",["OpenELMForCausalLM",So]],["qwen2",["Qwen2ForCausalLM",ko]],["phi",["PhiForCausalLM",Oo]],["phi3",["Phi3ForCausalLM",Lo]],["mpt",["MptForCausalLM",No]],["opt",["OPTForCausalLM",Uo]],["mbart",["MBartForCausalLM",xr]],["mistral",["MistralForCausalLM",nM]],["starcoder2",["Starcoder2ForCausalLM",oM]],["falcon",["FalconForCausalLM",lM]],["trocr",["TrOCRForCausalLM",rM]],["stablelm",["StableLmForCausalLM",_M]],["phi3_v",["Phi3VForCausalLM",Ns]]]),ux=new Map([["multi_modality",["MultiModalityCausalLM",OM]]]),n0=new Map([["bert",["BertForMaskedLM",Ie]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",Ue]],["electra",["ElectraForMaskedLM",Os]],["esm",["EsmForMaskedLM",Zs]],["convbert",["ConvBertForMaskedLM",jt]],["camembert",["CamembertForMaskedLM",xs]],["deberta",["DebertaForMaskedLM",et]],["deberta-v2",["DebertaV2ForMaskedLM",hs]],["mpnet",["MPNetForMaskedLM",zr]],["albert",["AlbertForMaskedLM",j]],["distilbert",["DistilBertForMaskedLM",Js]],["roberta",["RobertaForMaskedLM",Rt]],["xlm",["XLMWithLMHeadModel",rn]],["xlm-roberta",["XLMRobertaForMaskedLM",Ra]],["mobilebert",["MobileBertForMaskedLM",Ls]],["squeezebert",["SqueezeBertForMaskedLM",fr]]]),i0=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",ct]],["electra",["ElectraForQuestionAnswering",qr]],["convbert",["ConvBertForQuestionAnswering",Fs]],["camembert",["CamembertForQuestionAnswering",Ds]],["deberta",["DebertaForQuestionAnswering",zt]],["deberta-v2",["DebertaV2ForQuestionAnswering",fs]],["mpnet",["MPNetForQuestionAnswering",Ar]],["albert",["AlbertForQuestionAnswering",F]],["distilbert",["DistilBertForQuestionAnswering",Xs]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",za]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Wi]],["mobilebert",["MobileBertForQuestionAnswering",Ir]],["squeezebert",["SqueezeBertForQuestionAnswering",Pn]]]),vu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",qi]],["idefics3",["Idefics3ForConditionalGeneration",Hn]],["smolvlm",["SmolVLMForConditionalGeneration",qn]]]),o0=new Map([["llava",["LlavaForConditionalGeneration",Kn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Ha]],["moondream1",["Moondream1ForConditionalGeneration",qa]],["florence2",["Florence2ForConditionalGeneration",Qi]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Ao]],["idefics3",["Idefics3ForConditionalGeneration",Hn]],["smolvlm",["SmolVLMForConditionalGeneration",qn]],["paligemma",["PaliGemmaForConditionalGeneration",Ji]]]),a0=new Map([["ultravox",["UltravoxModel",VM]]]),px=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",qi]]]),l0=new Map([["vit",["ViTForImageClassification",Wo]],["ijepa",["IJepaForImageClassification",Ko]],["pvt",["PvtForImageClassification",Xo]],["vit_msn",["ViTMSNForImageClassification",pl]],["fastvit",["FastViTForImageClassification",_l]],["mobilevit",["MobileViTForImageClassification",Ml]],["mobilevitv2",["MobileViTV2ForImageClassification",vl]],["beit",["BeitForImageClassification",Sl]],["deit",["DeiTForImageClassification",Rl]],["hiera",["HieraForImageClassification",c]],["convnext",["ConvNextForImageClassification",iy]],["convnextv2",["ConvNextV2ForImageClassification",ay]],["dinov2",["Dinov2ForImageClassification",dy]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",uy]],["resnet",["ResNetForImageClassification",C]],["swin",["SwinForImageClassification",se]],["segformer",["SegformerForImageClassification",hM]],["efficientnet",["EfficientNetForImageClassification",wM]],["mobilenet_v1",["MobileNetV1ForImageClassification",MM]],["mobilenet_v2",["MobileNetV2ForImageClassification",xM]],["mobilenet_v3",["MobileNetV3ForImageClassification",PM]],["mobilenet_v4",["MobileNetV4ForImageClassification",$M]]]),d0=new Map([["detr",["DetrForObjectDetection",kl]],["rt_detr",["RTDetrForObjectDetection",Fl]],["table-transformer",["TableTransformerForObjectDetection",Ll]],["yolos",["YolosForObjectDetection",fy]]]),c0=new Map([["owlvit",["OwlViTForObjectDetection",Tl]],["owlv2",["Owlv2ForObjectDetection",Pl]],["grounding-dino",["GroundingDinoForObjectDetection",hy]]]),Ei=new Map([["detr",["DetrForSegmentation",na]],["clipseg",["CLIPSegForImageSegmentation",eo]]]),u0=new Map([["segformer",["SegformerForSemanticSegmentation",mM]],["sapiens",["SapiensForSemanticSegmentation",Hw]],["swin",["SwinForSemanticSegmentation",ye]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",bM]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",TM]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",CM]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",kM]]]),p0=new Map([["detr",["DetrForSegmentation",na]],["maskformer",["MaskFormerForInstanceSegmentation",Zw]]]),h0=new Map([["sam",["SamModel",wy]]]),m0=new Map([["wav2vec2",["Wav2Vec2ForCTC",Ey]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ny]],["unispeech",["UniSpeechForCTC",Fy]],["unispeech-sat",["UniSpeechSatForCTC",Ly]],["wavlm",["WavLMForCTC",Ky]],["hubert",["HubertForCTC",Vy]]]),f0=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Py]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",jy]],["unispeech",["UniSpeechForSequenceClassification",Oy]],["unispeech-sat",["UniSpeechSatForSequenceClassification",zy]],["wavlm",["WavLMForSequenceClassification",Hy]],["hubert",["HubertForSequenceClassification",Wy]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ua]]]),_0=new Map([["wavlm",["WavLMForXVector",qy]]]),g0=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",By]],["wavlm",["WavLMForAudioFrameClassification",Qy]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Cy]],["pyannote",["PyAnnoteForAudioFrameClassification",$y]]]),w0=new Map([["vitmatte",["VitMatteForImageMatting",wl]]]),hx=new Map([["patchtst",["PatchTSTForPrediction",RM]],["patchtsmixer",["PatchTSMixerForPrediction",jM]]]),y0=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ye]]]),M0=new Map([["dpt",["DPTForDepthEstimation",Bt]],["depth_anything",["DepthAnythingForDepthEstimation",an]],["glpn",["GLPNForDepthEstimation",ty]],["sapiens",["SapiensForDepthEstimation",qw]],["depth_pro",["DepthProForDepthEstimation",Jw]]]),b0=new Map([["sapiens",["SapiensForNormalEstimation",Qw]]]),v0=new Map([["vitpose",["VitPoseForPoseEstimation",qo]]]),x0=new Map([["clip",["CLIPVisionModelWithProjection",Qn]],["siglip",["SiglipVisionModel",el]],["jina_clip",["JinaCLIPVisionModel",il]]]),T0=[[ax,x.EncoderOnly],[lx,x.EncoderDecoder],[cx,x.DecoderOnly],[dx,x.AutoEncoder],[r0,x.EncoderOnly],[s0,x.EncoderOnly],[Mu,x.Seq2Seq],[yu,x.Seq2Seq],[bu,x.DecoderOnly],[ux,x.MultiModality],[n0,x.EncoderOnly],[i0,x.EncoderOnly],[vu,x.Vision2Seq],[o0,x.ImageTextToText],[a0,x.AudioTextToText],[l0,x.EncoderOnly],[Ei,x.EncoderOnly],[p0,x.EncoderOnly],[u0,x.EncoderOnly],[w0,x.EncoderOnly],[hx,x.EncoderOnly],[y0,x.EncoderOnly],[M0,x.EncoderOnly],[b0,x.EncoderOnly],[v0,x.EncoderOnly],[d0,x.EncoderOnly],[c0,x.EncoderOnly],[h0,x.MaskGeneration],[m0,x.EncoderOnly],[f0,x.EncoderOnly],[e0,x.Seq2Seq],[t0,x.EncoderOnly],[_0,x.EncoderOnly],[g0,x.EncoderOnly],[x0,x.EncoderOnly]];for(const[T,$]of T0)for(const[L,oe]of T.values())g.set(L,$),E.set(oe,L),M.set(L,oe);const mx=[["MusicgenForConditionalGeneration",_u,x.Musicgen],["Phi3VForCausalLM",Ns,x.Phi3V],["CLIPTextModelWithProjection",Ja,x.EncoderOnly],["SiglipTextModel",Za,x.EncoderOnly],["JinaCLIPTextModel",nl,x.EncoderOnly],["ClapTextModelWithProjection",cM,x.EncoderOnly],["ClapAudioModelWithProjection",uM,x.EncoderOnly],["DacEncoderModel",YM,x.EncoderOnly],["DacDecoderModel",ZM,x.EncoderOnly],["MimiEncoderModel",HM,x.EncoderOnly],["MimiDecoderModel",qM,x.EncoderOnly]];for(const[T,$,L]of mx)g.set(T,L),E.set($,T),M.set(T,$);const E0=new Map([["modnet",Ei],["birefnet",Ei],["isnet",Ei],["ben",Ei]]);for(const[T,$]of E0.entries())$.set(T,["PreTrainedModel",U]),g.set(T,x.EncoderOnly),E.set(U,T),M.set(T,U);class xu extends It{}re(xu,"MODEL_CLASS_MAPPINGS",T0.map($=>$[0])),re(xu,"BASE_IF_FAIL",!0);class P0 extends It{}re(P0,"MODEL_CLASS_MAPPINGS",[r0]);class C0 extends It{}re(C0,"MODEL_CLASS_MAPPINGS",[s0]);class S0 extends It{}re(S0,"MODEL_CLASS_MAPPINGS",[Mu]);class $0 extends It{}re($0,"MODEL_CLASS_MAPPINGS",[yu]);class k0 extends It{}re(k0,"MODEL_CLASS_MAPPINGS",[e0]);class I0 extends It{}re(I0,"MODEL_CLASS_MAPPINGS",[t0]);class A0 extends It{}re(A0,"MODEL_CLASS_MAPPINGS",[bu]);class F0 extends It{}re(F0,"MODEL_CLASS_MAPPINGS",[n0]);class O0 extends It{}re(O0,"MODEL_CLASS_MAPPINGS",[i0]);class D0 extends It{}re(D0,"MODEL_CLASS_MAPPINGS",[vu]);class L0 extends It{}re(L0,"MODEL_CLASS_MAPPINGS",[l0]);class z0 extends It{}re(z0,"MODEL_CLASS_MAPPINGS",[Ei]);class B0 extends It{}re(B0,"MODEL_CLASS_MAPPINGS",[u0]);class R0 extends It{}re(R0,"MODEL_CLASS_MAPPINGS",[p0]);class N0 extends It{}re(N0,"MODEL_CLASS_MAPPINGS",[d0]);class j0 extends It{}re(j0,"MODEL_CLASS_MAPPINGS",[c0]);class U0 extends It{}re(U0,"MODEL_CLASS_MAPPINGS",[h0]);class V0 extends It{}re(V0,"MODEL_CLASS_MAPPINGS",[m0]);class W0 extends It{}re(W0,"MODEL_CLASS_MAPPINGS",[f0]);class G0 extends It{}re(G0,"MODEL_CLASS_MAPPINGS",[_0]);class K0 extends It{}re(K0,"MODEL_CLASS_MAPPINGS",[g0]);class H0 extends It{}re(H0,"MODEL_CLASS_MAPPINGS",[px]);class q0 extends It{}re(q0,"MODEL_CLASS_MAPPINGS",[w0]);class Q0 extends It{}re(Q0,"MODEL_CLASS_MAPPINGS",[y0]);class X0 extends It{}re(X0,"MODEL_CLASS_MAPPINGS",[M0]);class J0 extends It{}re(J0,"MODEL_CLASS_MAPPINGS",[b0]);class Y0 extends It{}re(Y0,"MODEL_CLASS_MAPPINGS",[v0]);class Z0 extends It{}re(Z0,"MODEL_CLASS_MAPPINGS",[x0]);class eb extends It{}re(eb,"MODEL_CLASS_MAPPINGS",[o0]);class tb extends It{}re(tb,"MODEL_CLASS_MAPPINGS",[a0]);class fx extends pe{constructor({logits:$,past_key_values:L,encoder_outputs:oe,decoder_attentions:_e=null,cross_attentions:me=null}){super(),this.logits=$,this.past_key_values=L,this.encoder_outputs=oe,this.decoder_attentions=_e,this.cross_attentions=me}}class Mt extends pe{constructor({logits:$,...L}){super(),this.logits=$;const oe=Object.values(L);oe.length>0&&(this.attentions=oe)}}class rb extends pe{constructor({logits:$,embeddings:L}){super(),this.logits=$,this.embeddings=L}}class pr extends pe{constructor({logits:$}){super(),this.logits=$}}class wr extends pe{constructor({logits:$}){super(),this.logits=$}}class Pr extends pe{constructor({start_logits:$,end_logits:L}){super(),this.start_logits=$,this.end_logits=L}}class Fn extends pe{constructor({logits:$}){super(),this.logits=$}}class _x extends pe{constructor({logits:$,past_key_values:L}){super(),this.logits=$,this.past_key_values=L}}class sb extends pe{constructor({alphas:$}){super(),this.alphas=$}}class nb extends pe{constructor({waveform:$,spectrogram:L}){super(),this.waveform=$,this.spectrogram=L}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,d=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;p{t.r(r),t.d(r,{AutoFeatureExtractor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class o{static async from_pretrained(l,d={}){const p=await(0,i.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,d),u=p.feature_extractor_type,h=n[u];if(!h)throw new Error(`Unknown feature_extractor_type: '${u}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new h(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),o=t("./src/models/image_processors.js");class a{static async from_pretrained(d,p={}){const u=await(0,i.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,p),h=u.image_processor_type??u.feature_extractor_type;let w=o[h];return w||(h!==void 0&&console.warn(`Image processor type '${h}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),w=n.ImageProcessor),new w(u)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>d});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),o=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class d{static async from_pretrained(u,h={}){const w=await(0,i.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,h),{image_processor_type:_,feature_extractor_type:P,processor_class:A}=w;if(A&&o[A])return o[A].from_pretrained(u,h);if(!_&&!P)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const v={};if(_){const S=a[_];if(!S)throw new Error(`Unknown image_processor_type: '${_}'.`);v.image_processor=new S(w)}if(P){const S=a[P];if(S)v.image_processor=new S(w);else{const x=l[P];if(!x)throw new Error(`Unknown feature_extractor_type: '${P}'.`);v.feature_extractor=new x(w)}}const y={};return new n.Processor(y,v)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,i.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,i.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,i.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,d,p){let u;const h=a.length-l;if(h>0)if(d==="rand_trunc"){const w=Math.floor(Math.random()*(h+1));a=a.subarray(w,w+l),u=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${d}" not implemented`);else{if(h<0){let w=new Float64Array(l);if(w.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var d;const l=(d=this.size)==null?void 0:d.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[u,h]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(u,h,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends i{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>i});var s=t("./src/models/encodec/feature_extraction_encodec.js");class i extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>o,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const d=await super._call(l),p=[d.pixel_values.dims[0],64,64],u=(0,i.full)(p,1n);return{...d,pixel_mask:u}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class o extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(a,l,d,p={}){const[u,h,w]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(w).fill(_));let P=this.image_std;Array.isArray(P)||(P=new Array(w).fill(_));const A=_.map((v,y)=>-v/P[y]);return super.pad_image(a,l,d,{center:!0,constant_values:A,...p})}}class n extends i{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super(o),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const d=[1,l,a.length/l];return{input_values:new i.Tensor("float32",a,d)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>o.DacFeatureExtractor,EncodecFeatureExtractor:()=>i.EncodecFeatureExtractor,ImageFeatureExtractor:()=>_.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>p.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>u.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>h.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>w.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),i=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),o=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/speecht5/feature_extraction_speecht5.js"),u=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),h=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),w=t("./src/models/whisper/feature_extraction_whisper.js"),_=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{constructor(l,d){super(l,d);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:u,task_prompts_with_input:h}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(h??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const d=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))d.push(this.task_prompts_without_inputs.get(p));else{for(const[u,h]of this.task_prompts_with_input)if(p.includes(u)){d.push(h.replaceAll("{input}",p).replaceAll(u,""));break}d.length!==l.length&&d.push(p)}return d}post_process_generation(l,d,p){const u=this.tasks_answer_post_processing_type.get(d)??"pure_text";l=l.replaceAll("","").replaceAll("","");let h;switch(u){case"pure_text":h=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const w=u==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[w]),P=[],A=[];for(const[v,y,...S]of _)P.push(y?y.trim():P.at(-1)??""),A.push(S.map((x,g)=>(Number(x)+.5)/this.size_per_bin*p[g%2]));h={labels:P,[w]:A};break;default:throw new Error(`Task "${d}" (of type "${u}") not yet implemented.`)}return{[d]:h}}async _call(l,d=null,p={}){if(!l&&!d)throw new Error("Either text or images must be provided");const u=await this.image_processor(l,p),h=d?this.tokenizer(d,p):{};return{...u,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),d=l.pixel_values.dims,p=(0,i.ones)([d[0],d[2],d[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/image_processors_utils.js");function a(d,p){const h=d.dims.at(-1)-1,w=d.tolist();w.fill(!1,0,1),w.fill(!1,h);const _=p.tolist();return w.map((P,A)=>P?A:null).filter(P=>P!==null).map(P=>_[P])}class l extends s.Processor{async _call(p,u,h={}){const w=p?await this.image_processor(p,h):{};return{...u?this.tokenizer(u,h):{},...w}}post_process_grounded_object_detection(p,u,{box_threshold:h=.25,text_threshold:w=.25,target_sizes:_=null}={}){const{logits:P,pred_boxes:A}=p,v=P.dims[0];if(_!==null&&_.length!==v)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const y=P.dims.at(1),S=P.sigmoid(),x=S.max(-1).tolist(),g=A.tolist().map(E=>E.map(k=>(0,o.center_to_corners_format)(k))),M=[];for(let E=0;EV.map((Y,H)=>Y*k[(H+1)%2])));const B=x[E],R=[],J=[],q=[];for(let V=0;V{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[d,p]=a.dims.slice(-2);const u=p/d;return p>=d?(p=Math.ceil(p/l)*l,d=Math.floor(p/u),d=Math.ceil(d/l)*l):(d=Math.ceil(d/l)*l,p=Math.floor(d*u),p=Math.ceil(p/l)*l),{height:d,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:d=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let u=[],h=[],w=[];const _=[],P=[];for(const E of p){let k=await Promise.all(E.map(J=>this.preprocess(J)));_.push(...k.map(J=>J.original_size)),P.push(...k.map(J=>J.reshaped_input_size)),k.forEach(J=>J.pixel_values.unsqueeze_(0));const{longest_edge:B}=this.max_image_size;let R;if(l??this.do_image_splitting){let J=new Array(k.length),q=new Array(k.length);R=await Promise.all(k.map(async(V,Y)=>{const H=this.get_resize_for_vision_encoder(V.pixel_values,B),Q=await(0,i.interpolate_4d)(V.pixel_values,{size:[H.height,H.width]}),{frames:ie,num_splits_h:le,num_splits_w:ae}=await this.split_image(Q,this.max_image_size);return J[Y]=le,q[Y]=ae,(0,i.cat)(ie,0)})),h.push(J),w.push(q)}else{const J=[B,B];R=await Promise.all(k.map(q=>(0,i.interpolate_4d)(q.pixel_values,{size:J}))),h.push(new Array(k.length).fill(0)),w.push(new Array(k.length).fill(0))}u.push((0,i.cat)(R,0))}const A=u.length,[v,y,S,x]=u[0].dims;let g,M;if(A===1)g=u[0].unsqueeze_(0),M=(0,i.full)([A,v,S,x],!0);else{const E=Math.max(...u.map(R=>R.dims.at(0)));M=(0,i.full)([A,E,S,x],!0);const k=M.data,B=E*S*x;for(let R=0;Rd||w>p){_=Math.ceil(h/d),P=Math.ceil(w/p);const A=Math.ceil(h/_),v=Math.ceil(w/P);for(let x=0;x<_;++x)for(let g=0;g{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var o=t("./src/utils/core.js");function a(u,h,w,_,P,A){let v="";for(let y=0;y`+P.repeat(u);v+=` -`}return v+=` -${_}${A}`+P.repeat(u)+`${_}`,v}function l(u,h,w,_){return`${h}${_}`+w.repeat(u)+`${h}`}function d(u,h,w,_,P,A){return u===0&&h===0?l(w,_,P,A):a(w,u,h,_,P,A)}class p extends s.Processor{constructor(){super(...arguments);re(this,"fake_image_token","");re(this,"image_token","");re(this,"global_img_token","")}async _call(w,_=null,P={}){P.return_row_col_info??(P.return_row_col_info=!0);let A;_&&(A=await this.image_processor(_,P)),Array.isArray(w)||(w=[w]);const v=A.rows??[new Array(w.length).fill(0)],y=A.cols??[new Array(w.length).fill(0)],S=this.config.image_seq_len,x=[],g=[];for(let E=0;Ed(Y,R[H],S,this.fake_image_token,this.image_token,this.global_img_token)),q=k.split(this.image_token);if(q.length===0)throw new Error("The image token should be present in the text.");let V=q[0];for(let Y=0;Y{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>i.BitImageProcessor,CLIPFeatureExtractor:()=>o.CLIPFeatureExtractor,CLIPImageProcessor:()=>o.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>d.DetrFeatureExtractor,DetrImageProcessor:()=>d.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>h.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>w.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>P.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>y.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>x.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>x.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>g.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>g.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>E.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>E.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>k.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>k.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>B.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>B.MobileViTImageProcessor,NougatImageProcessor:()=>R.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>J.Owlv2ImageProcessor,Phi3VImageProcessor:()=>V.Phi3VImageProcessor,PvtImageProcessor:()=>Y.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Q.RTDetrImageProcessor,SamImageProcessor:()=>ie.SamImageProcessor,SegformerFeatureExtractor:()=>le.SegformerFeatureExtractor,SegformerImageProcessor:()=>le.SegformerImageProcessor,SiglipImageProcessor:()=>ae.SiglipImageProcessor,SmolVLMImageProcessor:()=>ge.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>N.Swin2SRImageProcessor,VLMImageProcessor:()=>A.VLMImageProcessor,ViTFeatureExtractor:()=>O.ViTFeatureExtractor,ViTImageProcessor:()=>O.ViTImageProcessor,VitMatteImageProcessor:()=>G.VitMatteImageProcessor,VitPoseImageProcessor:()=>ne.VitPoseImageProcessor,YolosFeatureExtractor:()=>X.YolosFeatureExtractor,YolosImageProcessor:()=>X.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),i=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),o=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),d=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),h=t("./src/models/efficientnet/image_processing_efficientnet.js"),w=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),P=t("./src/models/idefics3/image_processing_idefics3.js"),A=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),y=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),x=t("./src/models/maskformer/image_processing_maskformer.js"),g=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),E=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),k=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),B=t("./src/models/mobilevit/image_processing_mobilevit.js"),R=t("./src/models/nougat/image_processing_nougat.js"),J=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),V=t("./src/models/phi3_v/image_processing_phi3_v.js"),Y=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Q=t("./src/models/rt_detr/image_processing_rt_detr.js"),ie=t("./src/models/sam/image_processing_sam.js"),le=t("./src/models/segformer/image_processing_segformer.js"),ae=t("./src/models/siglip/image_processing_siglip.js"),ge=t("./src/models/smolvlm/image_processing_smolvlm.js"),N=t("./src/models/swin2sr/image_processing_swin2sr.js"),O=t("./src/models/vit/image_processing_vit.js"),G=t("./src/models/vitmatte/image_processing_vitmatte.js"),ne=t("./src/models/vitpose/image_processing_vitpose.js"),X=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super({do_pad:!0,pad_size:{width:o.image_size,height:o.image_size},...o}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(o,a,l,d){return super.pad_image(o,a,l,{constant_values:this.constant_values,center:!0,...d})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>d});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class d extends s.Processor{constructor(u,h){super(u,h),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(u,{images:h=null,chat_template:w="default"}={}){h?Array.isArray(h)||(h=[h]):h=await Promise.all(u.filter(R=>R.images).flatMap(R=>R.images).map(R=>l.RawImage.read(R)));const _=this.tokenizer,P=_.apply_chat_template(u,{tokenize:!1,add_generation_prompt:!0,chat_template:w}),A=R=>_.encode(R,{add_special_tokens:!1}),v=P.split(this.image_tag),y=v.length-1;if(h.length!==y)throw new Error(`Number of images provided (${h.length}) does not match number of "${this.image_tag}" image tags (${y})`);const[S,x,g]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=A(v[0]),E=new Array(M.length).fill(!1);for(let R=1;R0){const R=await this.image_processor(h);return R.pixel_values.unsqueeze_(0),{...B,...R}}return B}}re(d,"image_processor_class",i.AutoImageProcessor),re(d,"tokenizer_class",n.AutoTokenizer),re(d,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){const{resize_mode:a,fill_color:l,interpolation:d,size:p,...u}=o,h=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},w=d==="bicubic"?3:2;super({...u,size:h,resample:w,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{async _call(l=null,d=null,p={}){if(!l&&!d)throw new Error("Either text or images must be provided");const u=l?this.tokenizer(l,p):{},h=d?await this.image_processor(d,p):{};return{...u,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>i});var s=t("./src/models/maskformer/image_processing_maskformer.js");class i extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends i{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,u){if(!a.hasOwnProperty(u))throw new Error(`Format ${u} is not supported.`);const[h,w]=a[u],_=this[h].bind(this),[P,A]=p.dims,v=[],y=[],S=p.tolist();for(let g=0;g0?k.reduce((R,J)=>R*J,1):0;y.push(E),v.push(B)}return[_(y),v]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}batch_decode([p,u,h]){const[w,_]=this._decode_helper(p,"char"),[P,A]=this._decode_helper(u,"bpe"),[v,y]=this._decode_helper(h,"wp"),S=[],x=[];for(let g=0;g{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new i.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>i});var s=t("./src/models/donut/image_processing_donut.js");class i extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>i});var s=t("./src/models/owlvit/image_processing_owlvit.js");class i extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const o="";function a(d,p,u,h,w){return`${h.repeat(u*w)}${p}${d} -`}class l extends s.Processor{async _call(p,u=null,h={}){u||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),u=""),Array.isArray(p)||(p=[p]),Array.isArray(u)||(u=[u]);const w=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let P;u.some(y=>y.includes(o))?P=u.map(y=>{const S=y.replaceAll(o,o.repeat(_)),x=S.lastIndexOf(o),g=x===-1?0:x+o.length;return S.slice(0,g)+w+S.slice(g)+` -`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),P=u.map(y=>a(y,w,_,o,p.length)));const A=this.tokenizer(P,h);return{...await this.image_processor(p,h),...A}}}re(l,"tokenizer_class",n.AutoTokenizer),re(l,"image_processor_class",i.AutoImageProcessor),re(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");const n=336,o=[2,3],{ceil:a,floor:l,sqrt:d}=Math;class p extends s.ImageProcessor{constructor(h){super({...h,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=h.num_crops}calc_num_image_tokens_from_image_size(h,w){const{num_img_tokens:_}=this.config;return l((l(w/n)*l(h/n)+1)*_+1+(l(w/n)+1)*d(_))}get_resize_output_image_size(h,w){const _=this._num_crops,[P,A]=h.size;let v=P/A,y=1;for(;y*Math.ceil(y/v)<=_;)y+=1;y-=1;const S=Math.floor(y*336),x=Math.floor(S/v);return[S,x]}pad_image(h,w,_,P={}){const[A,v]=w,y=n*a(A/n),S=n*a(v/n),x=[1,1,1].map((g,M)=>(g-this.image_mean[M])/this.image_std[M]);return super.pad_image(h,w,{width:S,height:y},{center:!0,constant_values:x,...P})}async _call(h,{num_crops:w=null}={}){if(this._num_crops=w??(w=this.config.num_crops),w<4||d(w)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(h)||(h=[h]);const _=h.length,P=await Promise.all(h.map(E=>this.preprocess(E))),A=P.map(E=>E.original_size),v=P.map(E=>E.reshaped_input_size),y=[];for(const{pixel_values:E}of P){E.unsqueeze_(0);const[k,B]=E.dims.slice(-2),R=await(0,i.interpolate_4d)(E,{size:[n,n],mode:"bicubic"});if(w>0){const J=[],q=d(w),V=l(B/q),Y=l(k/q);for(let Q=0;QE.map(k=>n*a(k/n))),g=new i.Tensor("int64",x.flat(),[_,2]),M=x.map(([E,k])=>this.calc_num_image_tokens_from_image_size(k,E));return{pixel_values:S,original_sizes:A,reshaped_input_sizes:v,image_sizes:g,num_img_tokens:M}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const o="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,u=null,{padding:h=!0,truncation:w=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let P,A;if(u){A=await this.image_processor(u,{num_crops:_});const{num_img_tokens:v}=A,y=p.map((x,g)=>x.split(a).join(o.repeat(v[g])));P=this.tokenizer(y,{padding:h,truncation:w});const S=this.tokenizer.model.convert_tokens_to_ids([o])[0];P.input_ids.map_(x=>x==S?-x:x)}else P=this.tokenizer(p);return{...P,...A}}}re(l,"image_processor_class",i.AutoImageProcessor),re(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>i.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>h.PaliGemmaProcessor,Phi3VProcessor:()=>u.Phi3VProcessor,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>P.SamProcessor,SmolVLMProcessor:()=>A.SmolVLMProcessor,SpeechT5Processor:()=>v.SpeechT5Processor,UltravoxProcessor:()=>y.UltravoxProcessor,VLChatProcessor:()=>o.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>x.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>g.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),i=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),o=t("./src/models/janus/processing_janus.js"),a=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),u=t("./src/models/phi3_v/processing_phi3_v.js"),h=t("./src/models/paligemma/processing_paligemma.js"),w=t("./src/models/pyannote/processing_pyannote.js"),_=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),P=t("./src/models/sam/processing_sam.js"),A=t("./src/models/smolvlm/processing_smolvlm.js"),v=t("./src/models/speecht5/processing_speecht5.js"),y=t("./src/models/ultravox/processing_ultravox.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),x=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),g=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const d=[1,1,l.length];return{input_values:new i.Tensor("float32",l,d)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,d){const p=d/this.samples_to_frames(d)/this.config.sampling_rate,u=[];for(const h of l.tolist()){const w=[];let _=-1;for(let P=0;P({id:P,start:A*p,end:v*p,confidence:y/(v-A)})))}return u}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),i=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}re(n,"feature_extractor_class",i.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:d,original_sizes:p,reshaped_input_sizes:u}=await super._call(a,...l);let h=d;const{temporal_patch_size:w,merge_size:_,patch_size:P}=this.config;h.dims[0]===1&&(h=(0,i.cat)(Array.from({length:w},()=>h),0));const A=h.dims[0]/w,v=h.dims[1],y=Math.floor(h.dims[2]/P),S=Math.floor(h.dims[3]/P),x=h.view(A,w,v,Math.floor(y/_),_,P,Math.floor(S/_),_,P).permute(0,3,6,4,7,2,1,5,8).view(A*y*S,v*w*P*P),g=new i.Tensor("int64",[A,y,S],[1,3]);return{pixel_values:x,image_grid_thw:g,original_sizes:p,reshaped_input_sizes:u}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class o extends s.Processor{async _call(l,d=null,...p){Array.isArray(l)||(l=[l]);let u,h;if(d&&(u=await this.image_processor(d),h=u.image_grid_thw),h){let _=this.image_processor.config.merge_size**2,P=0;const A=h.tolist();l=l.map(v=>{for(;v.includes("<|image_pad|>");){const y=Number(A[P++].reduce((S,x)=>S*x,1n));v=v.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(y/_)))}return v.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...u}}}re(o,"image_processor_class",i.AutoImageProcessor),re(o,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...o){return(0,s.post_process_object_detection)(...o)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{reshape_input_points(l,d,p,u=!1){l=structuredClone(l);let h=(0,i.calculateDimensions)(l);if(h.length===3)u||(h=[1,...h]),l=[l];else if(h.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let w=0;wu!==d.dims[h]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:d=null,input_labels:p=null,input_boxes:u=null}={}){const h=await super._call(l);if(d&&(h.input_points=this.reshape_input_points(d,h.original_sizes,h.reshaped_input_sizes)),p){if(!h.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");h.input_labels=this.add_input_labels(p,h.input_points)}return u&&(h.input_boxes=this.reshape_input_points(u,h.original_sizes,h.reshaped_input_sizes,!0)),h}async post_process_masks(l,d,p,{mask_threshold:u=0,binarize:h=!0,pad_size:w=null}={}){const _=[];w=w??this.pad_size;const P=[w.height,w.width];for(let A=0;Au&&(g[M]=1);S=new n.Tensor("bool",g,S.dims)}_.push(S)}return _}generate_crop_boxes(l,d,{crop_n_layers:p=0,overlap_ratio:u=512/1500,points_per_crop:h=32,crop_n_points_downscale_factor:w=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}re(n,"image_processor_class",i.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(l){super(l);const d=this.config.sampling_rate,p=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(d/2),d,null,"kaldi",!0);for(let u=0;up*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:d,transpose:!0})}async _call(l,{padding:d=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:u=!0,return_attention_mask:h=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let w=await this._extract_fbank_features(l,this.config.max_length);if(u){const[g,M]=w.dims,E=w.data;for(let k=0;k0){const B=new Float32Array(M*(g+k));B.set(E),B.fill(this.config.padding_value,E.length);const R=g+k;w=new i.Tensor(w.type,B,[R,M]),h&&(_=new i.Tensor("int64",new BigInt64Array(R),[1,R]),_.data.fill(1n,0,g))}}const[P,A]=w.dims,v=this.config.stride;if(P%v!==0)throw new Error(`The number of frames (${P}) must be a multiple of the stride (${v}).`);const S=w.view(1,Math.floor(P/v),A*v),x={input_features:S};if(h){const g=S.dims[1],M=new BigInt64Array(g);if(_){const E=_.data;for(let k=1,B=0;k{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends i{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");class i extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class o extends s.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(o,a,l,d={}){const[p,u,h]=a;return super.pad_image(o,a,{width:u+(l-u%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...d})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l,d=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let u={};if(d){const w=d.length,{input_features:_}=await this.feature_extractor(d,{...p,max_length:w}),P=Math.round(w/this.config.encoder_ds_factor+1e-4),A=1+Math.ceil(P/this.config.stack_factor);u.audio_token_len=[A],u.audio_values=_;const v=this.config.audio_placeholder;if(!l.includes(v))throw new Error(`The input text does not contain the image token ${v}.`);l=l.replaceAll(v,v.repeat(A))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...u}}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor),re(o,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const d=await Promise.all(a.map(h=>this.preprocess(h))),p=await Promise.all(l.map(h=>this.preprocess(h,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,i.stack)(d.map((h,w)=>(0,i.cat)([h.pixel_values,p[w].pixel_values],0)),0),original_sizes:d.map(h=>h.original_size),reshaped_input_sizes:d.map(h=>h.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_pose_estimation(o,a,{threshold:l=null}={}){const d=o.tolist(),[p,u,h,w]=o.dims,_=[];for(let P=0;P{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const d=a.reduce((u,h)=>u+h,0)/a.length,p=a.reduce((u,h)=>u+(h-d)**2,0)/a.length;return a.map(u=>(u-d)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const d=[1,l.length];return{input_values:new i.Tensor("float32",l,d),attention_mask:new i.Tensor("int64",new BigInt64Array(l.length).fill(1n),d)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,d=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;pl*32768),(0,i.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const d=l.mean(1).data,p=l.data,[u,h,w]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>i,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>o});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],i=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function o(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const d=a.match(/^<\|([a-z]{2})\|>$/);if(d&&(a=d[1]),i.has(a))l=a;else{const u=a.length===2?i.keys():i.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(u))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{constructor(l){var d;super(l),(d=this.config).mel_filters??(d.mel_filters=(0,i.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,i.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const d=await(0,i.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=d.data,u=(0,n.max)(p)[0];for(let h=0;hu?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,u)):(p=new Float32Array(u),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>i});var s=t("./src/generation/configuration_utils.js");class i extends s.GenerationConfig{constructor(){super(...arguments);re(this,"return_timestamps",null);re(this,"return_token_timestamps",null);re(this,"num_frames",null);re(this,"alignment_heads",null);re(this,"task",null);re(this,"language",null);re(this,"no_timestamps_token_id",null);re(this,"prompt_ids",null);re(this,"is_multilingual",null);re(this,"lang_to_id",null);re(this,"task_to_id",null);re(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),i=t("./src/utils/tensor.js"),n=t("./src/env.js");const o=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(d,p,u)=>{const h=await(0,s.createInferenceSession)(new Uint8Array(d),p);let w=Promise.resolve();return async _=>{const P=(0,s.isONNXProxy)(),A=Object.fromEntries(Object.entries(_).map(([y,S])=>[y,(P?S.clone():S).ort_tensor])),v=await(w=o?w.then(()=>h.run(A)):h.run(A));return Array.isArray(u)?u.map(y=>new i.Tensor(v[y])):new i.Tensor(v[u])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}re(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>q,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>le,DepthEstimationPipeline:()=>X,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>R,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>Q,ImageFeatureExtractionPipeline:()=>J,ImageSegmentationPipeline:()=>ie,ImageToImagePipeline:()=>ne,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ge,Pipeline:()=>P,QuestionAnsweringPipeline:()=>y,SummarizationPipeline:()=>g,Text2TextGenerationPipeline:()=>x,TextClassificationPipeline:()=>A,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>G,TokenClassificationPipeline:()=>v,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>V,ZeroShotClassificationPipeline:()=>B,ZeroShotImageClassificationPipeline:()=>ae,ZeroShotObjectDetectionPipeline:()=>N,pipeline:()=>ke});var s=t("./src/tokenizers.js"),i=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var o=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),d=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),u=t("./src/utils/image.js");async function h(Me){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(K=>u.RawImage.read(K)))}async function w(Me,K){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(U=>typeof U=="string"||U instanceof URL?(0,d.read_audio)(U,K):U instanceof Float64Array?new Float32Array(U):U))}function _(Me,K){K&&(Me=Me.map(Fe=>Fe|0));const[U,pe,Pe,Ee]=Me;return{xmin:U,ymin:pe,xmax:Pe,ymax:Ee}}class P extends o.Callable{constructor({task:K,model:U,tokenizer:pe=null,processor:Pe=null}){super(),this.task=K,this.model=U,this.tokenizer=pe,this.processor=Pe}async dispose(){await this.model.dispose()}}class A extends P{constructor(K){super(K)}async _call(K,{top_k:U=1}={}){const pe=this.tokenizer(K,{padding:!0,truncation:!0}),Pe=await this.model(pe),Ee=this.model.config.problem_type==="multi_label_classification"?Le=>Le.sigmoid():Le=>new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),Fe=this.model.config.id2label,Ie=[];for(const Le of Pe.logits){const Ne=Ee(Le),Ve=await(0,p.topk)(Ne,U),D=Ve[0].tolist(),z=Ve[1].tolist().map((ee,ce)=>({label:Fe?Fe[ee]:`LABEL_${ee}`,score:D[ce]}));U===1?Ie.push(...z):Ie.push(z)}return Array.isArray(K)||U===1?Ie:Ie[0]}}class v extends P{constructor(K){super(K)}async _call(K,{ignore_labels:U=["O"]}={}){const pe=Array.isArray(K),Pe=this.tokenizer(pe?K:[K],{padding:!0,truncation:!0}),Fe=(await this.model(Pe)).logits,Ie=this.model.config.id2label,Le=[];for(let Ne=0;NeAe==this.tokenizer.sep_token_id);Le[D].map((Ae,Ue)=>Ae==1&&(Ue===0||Ue>z&&Ne.findIndex(Qe=>Qe==Z[Ue])===-1));const ee=Ee[D].tolist(),ce=Fe[D].tolist();for(let Ae=1;AeUe==Z[Ae])!==-1)&&(ee[Ae]=-1/0,ce[Ae]=-1/0);const be=(0,l.softmax)(ee).map((Ae,Ue)=>[Ae,Ue]),ve=(0,l.softmax)(ce).map((Ae,Ue)=>[Ae,Ue]);be[0][0]=0,ve[0][0]=0;const Re=(0,a.product)(be,ve).filter(Ae=>Ae[0][1]<=Ae[1][1]).map(Ae=>[Ae[0][1],Ae[1][1],Ae[0][0]*Ae[1][0]]).sort((Ae,Ue)=>Ue[2]-Ae[2]);for(let Ae=0;Aeee==this.tokenizer.mask_token_id);if(Ne===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=Pe[Ie][Ne],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),U),Z=D[0].tolist(),z=D[1].tolist();Ee.push(z.map((ee,ce)=>{const be=Le.slice();return be[Ne]=ee,{score:Z[ce],token:Number(ee),token_str:this.tokenizer.decode([ee]),sequence:this.tokenizer.decode(be,{skip_special_tokens:!0})}}))}return Array.isArray(K)?Ee:Ee[0]}}class x extends P{constructor(U){super(U);re(this,"_key","generated_text")}async _call(U,pe={}){Array.isArray(U)||(U=[U]),this.model.config.prefix&&(U=U.map(Ne=>this.model.config.prefix+Ne));const Pe=this.model.config.task_specific_params;Pe&&Pe[this.task]&&Pe[this.task].prefix&&(U=U.map(Ne=>Pe[this.task].prefix+Ne));const Ee=this.tokenizer,Fe={padding:!0,truncation:!0};let Ie;this instanceof M&&"_build_translation_inputs"in Ee?Ie=Ee._build_translation_inputs(U,Fe,pe):Ie=Ee(U,Fe);const Le=await this.model.generate({...Ie,...pe});return Ee.batch_decode(Le,{skip_special_tokens:!0}).map(Ne=>({[this._key]:Ne}))}}class g extends x{constructor(U){super(U);re(this,"_key","summary_text")}}class M extends x{constructor(U){super(U);re(this,"_key","translation_text")}}function E(Me){return Array.isArray(Me)&&Me.every(K=>"role"in K&&"content"in K)}class k extends P{constructor(K){super(K)}async _call(K,U={}){let pe=!1,Pe=!1,Ee;if(typeof K=="string")Ee=K=[K];else if(Array.isArray(K)&&K.every(z=>typeof z=="string"))pe=!0,Ee=K;else{if(E(K))K=[K];else if(Array.isArray(K)&&K.every(E))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Pe=!0,Ee=K.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Fe=U.add_special_tokens??!1,Ie=Pe?!1:U.return_full_text??!0;this.tokenizer.padding_side="left";const Le=this.tokenizer(Ee,{add_special_tokens:Fe,padding:!0,truncation:!0}),Ne=await this.model.generate({...Le,...U}),Ve=this.tokenizer.batch_decode(Ne,{skip_special_tokens:!0});let D;!Ie&&Le.input_ids.dims.at(-1)>0&&(D=this.tokenizer.batch_decode(Le.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Z=Array.from({length:K.length},z=>[]);for(let z=0;z[U.toLowerCase(),pe])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(K,U,{hypothesis_template:pe="This example is {}.",multi_label:Pe=!1}={}){const Ee=Array.isArray(K);Ee||(K=[K]),Array.isArray(U)||(U=[U]);const Fe=U.map(Ne=>pe.replace("{}",Ne)),Ie=Pe||U.length===1,Le=[];for(const Ne of K){const Ve=[];for(const z of Fe){const ee=this.tokenizer(Ne,{text_pair:z,padding:!0,truncation:!0}),ce=await this.model(ee);Ie?Ve.push([ce.logits.data[this.contradiction_id],ce.logits.data[this.entailment_id]]):Ve.push(ce.logits.data[this.entailment_id])}const Z=(Ie?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,ee)=>[z,ee]).sort((z,ee)=>ee[0]-z[0]);Le.push({sequence:Ne,labels:Z.map(z=>U[z[1]]),scores:Z.map(z=>z[0])})}return Ee?Le:Le[0]}}class R extends P{constructor(K){super(K)}async _call(K,{pooling:U="none",normalize:pe=!1,quantize:Pe=!1,precision:Ee="binary"}={}){const Fe=this.tokenizer(K,{padding:!0,truncation:!0}),Ie=await this.model(Fe);let Le=Ie.last_hidden_state??Ie.logits??Ie.token_embeddings;if(U!=="none")if(U==="mean")Le=(0,p.mean_pooling)(Le,Fe.attention_mask);else if(U==="cls")Le=Le.slice(null,0);else throw Error(`Pooling method '${U}' not supported.`);return pe&&(Le=Le.normalize(2,-1)),Pe&&(Le=(0,p.quantize_embeddings)(Le,Ee)),Le}}class J extends P{constructor(K){super(K)}async _call(K,{pool:U=null}={}){const pe=await h(K),{pixel_values:Pe}=await this.processor(pe),Ee=await this.model({pixel_values:Pe});let Fe;if(U){if(!("pooler_output"in Ee))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Fe=Ee.pooler_output}else Fe=Ee.last_hidden_state??Ee.logits??Ee.image_embeds;return Fe}}class q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,Pe=await w(K,pe),Ee=this.model.config.id2label,Fe=[];for(const Ie of Pe){const Le=await this.processor(Ie),Ve=(await this.model(Le)).logits[0],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),U),Z=D[0].tolist(),ee=D[1].tolist().map((ce,be)=>({label:Ee?Ee[ce]:`LABEL_${ce}`,score:Z[be]}));Fe.push(ee)}return Array.isArray(K)?Fe:Fe[0]}}class V extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a sound of {}."}={}){const Pe=!Array.isArray(K);Pe&&(K=[K]);const Ee=U.map(Ve=>pe.replace("{}",Ve)),Fe=this.tokenizer(Ee,{padding:!0,truncation:!0}),Ie=this.processor.feature_extractor.config.sampling_rate,Le=await w(K,Ie),Ne=[];for(const Ve of Le){const D=await this.processor(Ve),Z=await this.model({...Fe,...D}),z=(0,l.softmax)(Z.logits_per_audio.data);Ne.push([...z].map((ee,ce)=>({score:ee,label:U[ce]})))}return Pe?Ne[0]:Ne}}class Y extends P{constructor(K){super(K)}async _call(K,U={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(K,U);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(K,U);case"moonshine":return this._call_moonshine(K,U);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(K,U){U.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),U.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(K);pe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,Ee=await w(K,Pe),Fe=[];for(const Ie of Ee){const Le=await this.processor(Ie),Ve=(await this.model(Le)).logits[0],D=[];for(const z of Ve)D.push((0,l.max)(z.data)[1]);const Z=this.tokenizer.decode(D);Fe.push({text:Z})}return pe?Fe[0]:Fe}async _call_whisper(K,U){const pe=U.return_timestamps??!1,Pe=U.chunk_length_s??0,Ee=U.force_full_sequences??!1;let Fe=U.stride_length_s??null;const Ie={...U};pe==="word"&&(Ie.return_token_timestamps=!0,Ie.return_timestamps=!1);const Le=!Array.isArray(K);Le&&(K=[K]);const Ne=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,D=this.processor.feature_extractor.config.sampling_rate,Z=await w(K,D),z=[];for(const ee of Z){let ce=[];if(Pe>0){if(Fe===null)Fe=Pe/6;else if(Pe<=Fe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Re=D*Pe,Ae=D*Fe,Ue=Re-2*Ae;let Qe=0;for(;;){const Xe=Qe+Re,ct=ee.subarray(Qe,Xe),xt=await this.processor(ct),nr=Qe===0,jt=Xe>=ee.length;if(ce.push({stride:[ct.length,nr?0:Ae,jt?0:Ae],input_features:xt.input_features,is_last:jt}),jt)break;Qe+=Ue}}else ce=[{stride:[ee.length,0,0],input_features:(await this.processor(ee)).input_features,is_last:!0}];for(const Re of ce){Ie.num_frames=Math.floor(Re.stride[0]/Ve);const Ae=await this.model.generate({inputs:Re.input_features,...Ie});pe==="word"?(Re.tokens=Ae.sequences.tolist()[0],Re.token_timestamps=Ae.token_timestamps.tolist()[0].map(Ue=>(0,l.round)(Ue,2))):Re.tokens=Ae[0].tolist(),Re.stride=Re.stride.map(Ue=>Ue/D)}const[be,ve]=this.tokenizer._decode_asr(ce,{time_precision:Ne,return_timestamps:pe,force_full_sequences:Ee});z.push({text:be,...ve})}return Le?z[0]:z}async _call_moonshine(K,U){const pe=!Array.isArray(K);pe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,Ee=await w(K,Pe),Fe=[];for(const Ie of Ee){const Le=await this.processor(Ie),Ne=Math.floor(Ie.length/Pe)*6,Ve=await this.model.generate({max_new_tokens:Ne,...U,...Le}),D=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Fe.push({text:D})}return pe?Fe[0]:Fe}}class H extends P{constructor(K){super(K)}async _call(K,U={}){const pe=Array.isArray(K),Pe=await h(K),{pixel_values:Ee}=await this.processor(Pe),Fe=[];for(const Ie of Ee){Ie.dims=[1,...Ie.dims];const Le=await this.model.generate({inputs:Ie,...U}),Ne=this.tokenizer.batch_decode(Le,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Fe.push(Ne)}return pe?Fe:Fe[0]}}class Q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=await h(K),{pixel_values:Pe}=await this.processor(pe),Ee=await this.model({pixel_values:Pe}),Fe=this.model.config.id2label,Ie=[];for(const Le of Ee.logits){const Ne=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),U),Ve=Ne[0].tolist(),Z=Ne[1].tolist().map((z,ee)=>({label:Fe?Fe[z]:`LABEL_${z}`,score:Ve[ee]}));Ie.push(Z)}return Array.isArray(K)?Ie:Ie[0]}}class ie extends P{constructor(K){super(K),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(K,{threshold:U=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:Pe=.8,label_ids_to_fuse:Ee=null,target_sizes:Fe=null,subtask:Ie=null}={}){if(Array.isArray(K)&&K.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Ne=await h(K),Ve=Ne.map(Re=>[Re.height,Re.width]),D=await this.processor(Ne),{inputNames:Z,outputNames:z}=this.model.sessions.model;if(!Z.includes("pixel_values")){if(Z.length!==1)throw Error(`Expected a single input name, but got ${Z.length} inputs: ${Z}.`);const Re=Z[0];if(Re in D)throw Error(`Input name ${Re} already exists in the inputs.`);D[Re]=D.pixel_values}const ee=await this.model(D);let ce=null;if(Ie!==null)ce=this.subtasks_mapping[Ie];else if(this.processor.image_processor){for(const[Re,Ae]of Object.entries(this.subtasks_mapping))if(Ae in this.processor.image_processor){ce=this.processor.image_processor[Ae].bind(this.processor.image_processor),Ie=Re;break}}const be=this.model.config.id2label,ve=[];if(Ie)if(Ie==="panoptic"||Ie==="instance"){const Re=ce(ee,U,pe,Pe,Ee,Fe??Ve)[0],Ae=Re.segmentation;for(const Ue of Re.segments_info){const Qe=new Uint8ClampedArray(Ae.data.length);for(let ct=0;ctct<0||ct>1)&&Qe.sigmoid_();const Xe=await u.RawImage.fromTensor(Qe.mul_(255).to("uint8")).resize(Ue[1],Ue[0]);ve.push({label:null,score:null,mask:Xe})}}return ve}}class le extends ie{constructor(K){super(K)}async _call(K,U={}){if(Array.isArray(K)&&K.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const Pe=await h(K),Ee=await super._call(K,U);return Pe.map((Ie,Le)=>{const Ne=Ie.clone();return Ne.putAlpha(Ee[Le].mask),Ne})}}class ae extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a photo of {}"}={}){const Pe=Array.isArray(K),Ee=await h(K),Fe=U.map(Z=>pe.replace("{}",Z)),Ie=this.tokenizer(Fe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Le}=await this.processor(Ee),Ne=await this.model({...Ie,pixel_values:Le}),Ve=this.model.config.model_type==="siglip"?Z=>Z.sigmoid().data:Z=>(0,l.softmax)(Z.data),D=[];for(const Z of Ne.logits_per_image){const ee=[...Ve(Z)].map((ce,be)=>({score:ce,label:U[be]}));ee.sort((ce,be)=>be.score-ce.score),D.push(ee)}return Pe?D:D[0]}}class ge extends P{constructor(K){super(K)}async _call(K,{threshold:U=.9,percentage:pe=!1}={}){const Pe=Array.isArray(K);if(Pe&&K.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ee=await h(K),Fe=pe?null:Ee.map(z=>[z.height,z.width]),{pixel_values:Ie,pixel_mask:Le}=await this.processor(Ee),Ne=await this.model({pixel_values:Ie,pixel_mask:Le}),Ve=this.processor.image_processor.post_process_object_detection(Ne,U,Fe),D=this.model.config.id2label,Z=Ve.map(z=>z.boxes.map((ee,ce)=>({score:z.scores[ce],label:D[z.classes[ce]],box:_(ee,!pe)})));return Pe?Z:Z[0]}}class N extends P{constructor(K){super(K)}async _call(K,U,{threshold:pe=.1,top_k:Pe=null,percentage:Ee=!1}={}){const Fe=Array.isArray(K),Ie=await h(K),Le=this.tokenizer(U,{padding:!0,truncation:!0}),Ne=await this.processor(Ie),Ve=[];for(let D=0;D({score:ve.scores[Ae],label:ve.labels[Ae],box:_(Re,!Ee)}))}else{const ve=this.processor.image_processor.post_process_object_detection(ce,pe,z,!0)[0];be=ve.boxes.map((Re,Ae)=>({score:ve.scores[Ae],label:U[ve.classes[Ae]],box:_(Re,!Ee)}))}be.sort((ve,Re)=>Re.score-ve.score),Pe!==null&&(be=be.slice(0,Pe)),Ve.push(be)}return Fe?Ve:Ve[0]}}class O extends P{constructor(K){super(K)}async _call(K,U,pe={}){const Pe=(await h(K))[0],{pixel_values:Ee}=await this.processor(Pe),Fe=`${U}`,Ie=this.tokenizer(Fe,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Le=await this.model.generate({inputs:Ee,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ie,...pe}),Ve=this.tokenizer.batch_decode(Le)[0].match(/(.*?)<\/s_answer>/);let D=null;return Ve&&Ve.length>=2&&(D=Ve[1].trim()),[{answer:D}]}}class G extends P{constructor(U){super(U);re(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=U.vocoder??null}async _call(U,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(U,{speaker_embeddings:pe}):this._call_text_to_waveform(U)}async _call_text_to_waveform(U){const pe=this.tokenizer(U,{padding:!0,truncation:!0}),{waveform:Pe}=await this.model(pe),Ee=this.model.config.sampling_rate;return new d.RawAudio(Pe.data,Ee)}async _call_text_to_spectrogram(U,{speaker_embeddings:pe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await i.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof pe=="string"||pe instanceof URL)&&(pe=new Float32Array(await(await fetch(pe)).arrayBuffer())),pe instanceof Float32Array)pe=new p.Tensor("float32",pe,[1,pe.length]);else if(!(pe instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Pe}=this.tokenizer(U,{padding:!0,truncation:!0}),{waveform:Ee}=await this.model.generate_speech(Pe,pe,{vocoder:this.vocoder}),Fe=this.processor.feature_extractor.config.sampling_rate;return new d.RawAudio(Ee.data,Fe)}}class ne extends P{constructor(K){super(K)}async _call(K){const U=await h(K),pe=await this.processor(U),Pe=await this.model(pe),Ee=[];for(const Fe of Pe.reconstruction){const Ie=Fe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ee.push(u.RawImage.fromTensor(Ie))}return Ee.length>1?Ee:Ee[0]}}class X extends P{constructor(K){super(K)}async _call(K){const U=await h(K),pe=await this.processor(U),{predicted_depth:Pe}=await this.model(pe),Ee=[];for(let Fe=0;Fe1?Ee:Ee[0]}}const we=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:v,model:i.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:y,model:i.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:i.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:g,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:x,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:k,model:i.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:B,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:q,model:i.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:V,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[i.AutoModelForSpeechSeq2Seq,i.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:G,model:[i.AutoModelForTextToWaveform,i.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:i.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Q,model:i.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ie,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:le,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:ae,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ge,model:i.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:N,model:i.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:O,model:i.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ne,model:i.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:X,model:i.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:R,model:i.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:J,model:[i.AutoModelForImageFeatureExtraction,i.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),fe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ke(Me,K=null,{progress_callback:U=null,config:pe=null,cache_dir:Pe=null,local_files_only:Ee=!1,revision:Fe="main",device:Ie=null,dtype:Le=null,subfolder:Ne="onnx",use_external_data_format:Ve=null,model_file_name:D=null,session_options:Z={}}={}){Me=fe[Me]??Me;const z=we[Me.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${Me}. Must be one of [${Object.keys(we)}]`);K||(K=z.default.model,console.log(`No model specified. Using default model: "${K}".`));const ee={progress_callback:U,config:pe,cache_dir:Pe,local_files_only:Ee,revision:Fe,device:Ie,dtype:Le,subfolder:Ne,use_external_data_format:Ve,model_file_name:D,session_options:Z},ce=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),be=await He(ce,K,ee);be.task=Me,(0,a.dispatchCallback)(U,{status:"ready",task:Me,model:K});const ve=z.pipeline;return new ve(be)}async function He(Me,K,U){const pe=Object.create(null),Pe=[];for(const[Ee,Fe]of Me.entries()){if(!Fe)continue;let Ie;Array.isArray(Fe)?Ie=new Promise(async(Le,Ne)=>{var D,Z;let Ve;for(const z of Fe){if(z===null){Le(null);return}try{Le(await z.from_pretrained(K,U));return}catch(ee){if((D=ee.message)!=null&&D.includes("Unsupported model type"))Ve=ee;else if((Z=ee.message)!=null&&Z.includes("Could not locate file"))Ve=ee;else{Ne(ee);return}}}Ne(Ve)}):Ie=Fe.from_pretrained(K,U),pe[Ee]=Ie,Pe.push(Ie)}await Promise.all(Pe);for(const[Ee,Fe]of Object.entries(pe))pe[Ee]=await Fe;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ur,AutoTokenizer:()=>Cn,BartTokenizer:()=>hs,BertTokenizer:()=>qr,BlenderbotSmallTokenizer:()=>Jr,BlenderbotTokenizer:()=>Ar,BloomTokenizer:()=>Qr,CLIPTokenizer:()=>Tn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>Xr,CodeLlamaTokenizer:()=>Qs,CohereTokenizer:()=>Pn,ConvBertTokenizer:()=>mr,DebertaTokenizer:()=>Ts,DebertaV2Tokenizer:()=>Es,DistilBertTokenizer:()=>et,ElectraTokenizer:()=>zt,EsmTokenizer:()=>Zs,FalconTokenizer:()=>_s,GPT2Tokenizer:()=>ps,GPTNeoXTokenizer:()=>Ys,GemmaTokenizer:()=>Lr,Grok1Tokenizer:()=>Cs,HerbertTokenizer:()=>Ds,LlamaTokenizer:()=>qs,M2M100Tokenizer:()=>zs,MBart50Tokenizer:()=>ms,MBartTokenizer:()=>Er,MPNetTokenizer:()=>Js,MarianTokenizer:()=>En,MgpstrTokenizer:()=>Ss,MobileBertTokenizer:()=>us,NllbTokenizer:()=>Ls,NougatTokenizer:()=>fr,PreTrainedTokenizer:()=>dt,Qwen2Tokenizer:()=>en,RoFormerTokenizer:()=>Be,RobertaTokenizer:()=>fs,SiglipTokenizer:()=>zr,SpeechT5Tokenizer:()=>cr,SqueezeBertTokenizer:()=>xs,T5Tokenizer:()=>kr,TokenizerModel:()=>J,VitsTokenizer:()=>Rs,Wav2Vec2CTCTokenizer:()=>Bs,WhisperTokenizer:()=>Ir,XLMRobertaTokenizer:()=>Xs,XLMTokenizer:()=>rr,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),i=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),d=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function u(ue,F){const j=await Promise.all([(0,n.getModelJSON)(ue,"tokenizer.json",!0,F),(0,n.getModelJSON)(ue,"tokenizer_config.json",!0,F)]);return F.legacy!==null&&(j[1].legacy=F.legacy),j}function h(ue,F){const j=[];let te=0;for(const de of ue.matchAll(F)){const he=de[0];te0&&j.push(he),te=de.index+he.length}return te=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function x(ue,F,j){const te=[];let de=0;for(;dethis.tokens_to_ids.get(j)??this.unk_token_id)}convert_ids_to_tokens(F){return F.map(j=>this.vocab[j]??this.unk_token)}}class q extends J{constructor(F){super(F),this.tokens_to_ids=_(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.max_input_chars_per_word=F.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[j,te]of this.tokens_to_ids)this.vocab[te]=j}encode(F){const j=[];for(const te of F){const de=[...te];if(de.length>this.max_input_chars_per_word){j.push(this.unk_token);continue}let he=!1,Ce=0;const We=[];for(;Ce0&&(Ze=this.config.continuing_subword_prefix+Ze),this.tokens_to_ids.has(Ze)){Ke=Ze;break}--qe}if(Ke===null){he=!0;break}We.push(Ke),Ce=qe}he?j.push(this.unk_token):j.push(...We)}return j}}class V extends J{constructor(F,j){super(F);const te=F.vocab.length;this.vocab=new Array(te),this.scores=new Array(te);for(let de=0;de[de,he])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=j.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,o.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(F){const j=F.chars,te=1;let de=0;for(;de{const ue=[...Array.from({length:94},(de,he)=>he+33),...Array.from({length:12},(de,he)=>he+161),...Array.from({length:82},(de,he)=>he+174)],F=ue.slice();let j=0;for(let de=0;de<256;++de)ue.includes(de)||(ue.push(de),F.push(256+j),j+=1);const te=F.map(de=>String.fromCharCode(de));return Object.fromEntries(ue.map((de,he)=>[de,te[he]]))})(),H=(0,i.reverseDictionary)(Y);class Q extends J{constructor(F){super(F),this.tokens_to_ids=_(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[te,de]of this.tokens_to_ids)this.vocab[de]=te;const j=Array.isArray(F.merges[0]);this.merges=j?F.merges:F.merges.map(te=>te.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((te,de)=>[JSON.stringify(te),de])),this.end_of_word_suffix=F.end_of_word_suffix,this.continuing_subword_suffix=F.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(F){if(F.length===0)return[];const j=this.cache.get(F);if(j!==void 0)return j;const te=Array.from(F);this.end_of_word_suffix&&(te[te.length-1]+=this.end_of_word_suffix);let de=[];if(te.length>1){const he=new l.PriorityQueue((qe,Ke)=>qe.score`<0x${We.toString(16).toUpperCase().padStart(2,"0")}>`);Ce.every(We=>this.tokens_to_ids.has(We))?j.push(...Ce):j.push(this.unk_token)}else j.push(this.unk_token)}return j}}class ie extends J{constructor(F,j){super(F),this.tokens_to_ids=_(j.target_lang?F.vocab[j.target_lang]:F.vocab),this.bos_token=j.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=j.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=j.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=j.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[te,de]of this.tokens_to_ids)this.vocab[de]=te}encode(F){return F}}class le extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"BertNormalizer":return new Me(F);case"Precompiled":return new jt(F);case"Sequence":return new He(F);case"Replace":return new ae(F);case"NFC":return new N(F);case"NFD":return new O(F);case"NFKC":return new G(F);case"NFKD":return new ne(F);case"Strip":return new X(F);case"StripAccents":return new we(F);case"Lowercase":return new fe(F);case"Prepend":return new ke(F);default:throw new Error(`Unknown Normalizer type: ${F.type}`)}}normalize(F){throw Error("normalize should be implemented in subclass.")}_call(F){return this.normalize(F)}}class ae extends le{normalize(F){const j=w(this.config.pattern);return j===null?F:F.replaceAll(j,this.config.content)}}class ge extends le{constructor(){super(...arguments);re(this,"form")}normalize(j){return j=j.normalize(this.form),j}}class N extends ge{constructor(){super(...arguments);re(this,"form","NFC")}}class O extends ge{constructor(){super(...arguments);re(this,"form","NFD")}}class G extends ge{constructor(){super(...arguments);re(this,"form","NFKC")}}class ne extends ge{constructor(){super(...arguments);re(this,"form","NFKD")}}class X extends le{normalize(F){return this.config.strip_left&&this.config.strip_right?F=F.trim():(this.config.strip_left&&(F=F.trimStart()),this.config.strip_right&&(F=F.trimEnd())),F}}class we extends le{normalize(F){return F=v(F),F}}class fe extends le{normalize(F){return F=F.toLowerCase(),F}}class ke extends le{normalize(F){return F=this.config.prepend+F,F}}class He extends le{constructor(F){super(F),this.normalizers=F.normalizers.map(j=>le.fromConfig(j))}normalize(F){return this.normalizers.reduce((j,te)=>te.normalize(j),F)}}class Me extends le{_tokenize_chinese_chars(F){const j=[];for(let te=0;tethis.pre_tokenize_text(te,j)):this.pre_tokenize_text(F,j)).flat()}_call(F,j){return this.pre_tokenize(F,j)}}class U extends K{constructor(F){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text(F,j){return F.trim().match(this.pattern)||[]}}class pe extends K{constructor(F){super(),this.config=F,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text(F,j){return this.add_prefix_space&&!F.startsWith(" ")&&(F=" "+F),(this.use_regex?F.match(this.pattern)||[]:[F]).map(de=>Array.from(this.text_encoder.encode(de),he=>this.byte_encoder[he]).join(""))}}class Pe extends K{constructor(F){super(),this.config=F,this.pattern=w(this.config.pattern,this.config.invert)}pre_tokenize_text(F,j){var te;return this.pattern===null?[]:this.config.invert?F.match(this.pattern)||[]:((te=this.config.behavior)==null?void 0:te.toLowerCase())==="removed"?F.split(this.pattern).filter(de=>de):h(F,this.pattern)}}class Ee extends K{constructor(F){super(),this.config=F,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text(F,j){return F.match(this.pattern)||[]}}class Fe extends K{constructor(F){super(),this.config=F;const j=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(j,"gu")}pre_tokenize_text(F,j){return F.match(this.pattern)||[]}}class Ie extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"TemplateProcessing":return new Ve(F);case"ByteLevel":return new D(F);case"RobertaProcessing":return new Ne(F);case"BertProcessing":return new Le(F);case"Sequence":return new Z(F);default:throw new Error(`Unknown PostProcessor type: ${F.type}`)}}post_process(F,...j){throw Error("post_process should be implemented in subclass.")}_call(F,...j){return this.post_process(F,...j)}}class Le extends Ie{constructor(F){super(F),this.cls=F.cls[0],this.sep=F.sep[0]}post_process(F,j=null,{add_special_tokens:te=!0}={}){te&&(F=(0,i.mergeArrays)([this.cls],F,[this.sep]));let de=new Array(F.length).fill(0);if(j!==null){const he=te&&this instanceof Ne?[this.sep]:[],Ce=te?[this.sep]:[];F=(0,i.mergeArrays)(F,he,j,Ce),de=(0,i.mergeArrays)(de,new Array(j.length+he.length+Ce.length).fill(1))}return{tokens:F,token_type_ids:de}}}class Ne extends Le{}class Ve extends Ie{constructor(F){super(F),this.single=F.single,this.pair=F.pair}post_process(F,j=null,{add_special_tokens:te=!0}={}){const de=j===null?this.single:this.pair;let he=[],Ce=[];for(const We of de)"SpecialToken"in We?te&&(he.push(We.SpecialToken.id),Ce.push(We.SpecialToken.type_id)):"Sequence"in We&&(We.Sequence.id==="A"?(he=(0,i.mergeArrays)(he,F),Ce=(0,i.mergeArrays)(Ce,new Array(F.length).fill(We.Sequence.type_id))):We.Sequence.id==="B"&&(he=(0,i.mergeArrays)(he,j),Ce=(0,i.mergeArrays)(Ce,new Array(j.length).fill(We.Sequence.type_id))));return{tokens:he,token_type_ids:Ce}}}class D extends Ie{post_process(F,j=null){return j&&(F=(0,i.mergeArrays)(F,j)),{tokens:F}}}class Z extends Ie{constructor(F){super(F),this.processors=F.processors.map(j=>Ie.fromConfig(j))}post_process(F,j=null,te={}){let de;for(const he of this.processors)if(he instanceof D)F=he.post_process(F).tokens,j&&(j=he.post_process(j).tokens);else{const Ce=he.post_process(F,j,te);F=Ce.tokens,de=Ce.token_type_ids}return{tokens:F,token_type_ids:de}}}class z extends s.Callable{constructor(F){super(),this.config=F,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=F.trim_offsets}static fromConfig(F){if(F===null)return null;switch(F.type){case"WordPiece":return new Re(F);case"Metaspace":return new nr(F);case"ByteLevel":return new Ae(F);case"Replace":return new ee(F);case"ByteFallback":return new ce(F);case"Fuse":return new be(F);case"Strip":return new ve(F);case"Sequence":return new Qe(F);case"CTC":return new Ue(F);case"BPEDecoder":return new Xe(F);default:throw new Error(`Unknown Decoder type: ${F.type}`)}}_call(F){return this.decode(F)}decode(F){return this.decode_chain(F).join("")}decode_chain(F){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends z{decode_chain(F){const j=w(this.config.pattern);return j===null?F:F.map(te=>te.replaceAll(j,this.config.content))}}class ce extends z{constructor(F){super(F),this.text_decoder=new TextDecoder}decode_chain(F){const j=[];let te=[];for(const de of F){let he=null;if(de.length===6&&de.startsWith("<0x")&&de.endsWith(">")){const Ce=parseInt(de.slice(3,5),16);isNaN(Ce)||(he=Ce)}if(he!==null)te.push(he);else{if(te.length>0){const Ce=this.text_decoder.decode(Uint8Array.from(te));j.push(Ce),te=[]}j.push(de)}}if(te.length>0){const de=this.text_decoder.decode(Uint8Array.from(te));j.push(de),te=[]}return j}}class be extends z{decode_chain(F){return[F.join("")]}}class ve extends z{constructor(F){super(F),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(F){return F.map(j=>{let te=0;for(let he=0;he(te!==0&&(j.startsWith(this.config.prefix)?j=j.replace(this.config.prefix,""):j=" "+j),this.cleanup&&(j=A(j)),j))}}class Ae extends z{constructor(F){super(F),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(F){const j=F.join(""),te=new Uint8Array([...j].map(he=>this.byte_decoder[he]));return this.text_decoder.decode(te)}decode_chain(F){const j=[];let te=[];for(const de of F)this.added_tokens.find(he=>he.content===de)!==void 0?(te.length>0&&(j.push(this.convert_tokens_to_string(te)),te=[]),j.push(de)):te.push(de);return te.length>0&&j.push(this.convert_tokens_to_string(te)),j}}class Ue extends z{constructor(F){super(F),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(F){if(F.length===0)return"";const j=[F[0]];for(let he=1;hehe!==this.pad_token).join("");return this.cleanup&&(de=A(de).replaceAll(this.word_delimiter_token," ").trim()),de}decode_chain(F){return[this.convert_tokens_to_string(F)]}}class Qe extends z{constructor(F){super(F),this.decoders=F.decoders.map(j=>z.fromConfig(j))}decode_chain(F){return this.decoders.reduce((j,te)=>te.decode_chain(j),F)}}class Xe extends z{constructor(F){super(F),this.suffix=this.config.suffix}decode_chain(F){return F.map((j,te)=>j.replaceAll(this.suffix,te===F.length-1?"":" "))}}class ct extends z{decode_chain(F){let j="";for(let te=1;tete.normalize("NFKC")).join("~"):F=F.normalize("NFKC"),F}}class dr extends K{constructor(F){super(),this.tokenizers=F.pretokenizers.map(j=>K.fromConfig(j))}pre_tokenize_text(F,j){return this.tokenizers.reduce((te,de)=>de.pre_tokenize(te,j),[F])}}class ds extends K{constructor(F){super()}pre_tokenize_text(F,j){return F.match(/\w+|[^\w\s]+/g)||[]}}class Fs extends K{constructor(F){super()}pre_tokenize_text(F,j){return g(F)}}class Dr extends K{constructor(F){super(),this.config=F,this.pattern=w(this.config.pattern),this.content=this.config.content}pre_tokenize_text(F,j){return this.pattern===null?[F]:[F.replaceAll(this.pattern,this.config.content)]}}const cs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Os(ue,F,j,te){for(const de of Object.keys(ue)){const he=F-ue[de].length,Ce=j(de),We=new Array(he).fill(Ce);ue[de]=te==="right"?(0,i.mergeArrays)(ue[de],We):(0,i.mergeArrays)(We,ue[de])}}function jr(ue,F){for(const j of Object.keys(ue))ue[j].length=F}class dt extends s.Callable{constructor(j,te){super();re(this,"return_token_type_ids",!1);re(this,"padding_side","right");this._tokenizer_config=te,this.normalizer=le.fromConfig(j.normalizer),this.pre_tokenizer=K.fromConfig(j.pre_tokenizer),this.model=J.fromConfig(j.model,te),this.post_processor=Ie.fromConfig(j.post_processor),this.decoder=z.fromConfig(j.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const de of j.added_tokens){const he=new R(de);this.added_tokens.push(he),this.model.tokens_to_ids.set(he.content,he.id),this.model.vocab[he.id]=he.content,he.special&&(this.special_tokens.push(he.content),this.all_special_ids.push(he.id))}if(this.additional_special_tokens=te.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((de,he)=>he.content.length-de.content.length).map(de=>`${de.lstrip?"\\s*":""}(${(0,i.escapeRegExp)(de.content)})${de.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=te.model_max_length,this.remove_space=te.remove_space,this.clean_up_tokenization_spaces=te.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=te.do_lowercase_and_remove_accent??!1,te.padding_side&&(this.padding_side=te.padding_side),this.legacy=!1,this.chat_template=te.chat_template??null,Array.isArray(this.chat_template)){const de=Object.create(null);for(const{name:he,template:Ce}of this.chat_template){if(typeof he!="string"||typeof Ce!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');de[he]=Ce}this.chat_template=de}this._compiled_template_cache=new Map}getToken(...j){for(const te of j){const de=this._tokenizer_config[te];if(de)if(typeof de=="object"){if(de.__type==="AddedToken")return de.content;throw Error(`Unknown token: ${de}`)}else return de}return null}static async from_pretrained(j,{progress_callback:te=null,config:de=null,cache_dir:he=null,local_files_only:Ce=!1,revision:We="main",legacy:qe=null}={}){const Ke=await u(j,{progress_callback:te,config:de,cache_dir:he,local_files_only:Ce,revision:We,legacy:qe});return new this(...Ke)}_call(j,{text_pair:te=null,add_special_tokens:de=!0,padding:he=!1,truncation:Ce=null,max_length:We=null,return_tensor:qe=!0,return_token_type_ids:Ke=null}={}){const Ze=Array.isArray(j);let ht;if(Ze){if(j.length===0)throw Error("text array must be non-empty");if(te!==null){if(Array.isArray(te)){if(j.length!==te.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");ht=j.map((kt,Wt)=>this._encode_plus(kt,{text_pair:te[Wt],add_special_tokens:de,return_token_type_ids:Ke}))}else ht=j.map(kt=>this._encode_plus(kt,{add_special_tokens:de,return_token_type_ids:Ke}))}else{if(j==null)throw Error("text may not be null or undefined");if(Array.isArray(te))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");ht=[this._encode_plus(j,{text_pair:te,add_special_tokens:de,return_token_type_ids:Ke})]}if(We===null?he==="max_length"?We=this.model_max_length:We=(0,o.max)(ht.map(kt=>kt.input_ids.length))[0]:Ce||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),We=Math.min(We,this.model_max_length??1/0),he||Ce)for(let kt=0;ktWe?Ce&&jr(ht[kt],We):he&&Os(ht[kt],We,Wt=>Wt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ct={};if(qe){if(!(he&&Ce)&&ht.some(Wt=>{var Ot;for(const Ut of Object.keys(Wt))if(Wt[Ut].length!==((Ot=ht[0][Ut])==null?void 0:Ot.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const kt=[ht.length,ht[0].input_ids.length];for(const Wt of Object.keys(ht[0]))Ct[Wt]=new a.Tensor("int64",BigInt64Array.from(ht.flatMap(Ot=>Ot[Wt]).map(BigInt)),kt)}else{for(const kt of Object.keys(ht[0]))Ct[kt]=ht.map(Wt=>Wt[kt]);if(!Ze)for(const kt of Object.keys(Ct))Ct[kt]=Ct[kt][0]}return Ct}_encode_text(j){return j===null?null:(this.added_tokens_regex?j.split(this.added_tokens_regex).filter(he=>he):[j]).map((he,Ce)=>{if(this.added_tokens.find(qe=>qe.content===he)!==void 0)return he;{if(this.remove_space===!0&&(he=he.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(he=y(he)),this.normalizer!==null&&(he=this.normalizer(he)),he.length===0)return[];const qe=this.pre_tokenizer!==null?this.pre_tokenizer(he,{section_index:Ce}):[he];return this.model(qe)}}).flat()}_encode_plus(j,{text_pair:te=null,add_special_tokens:de=!0,return_token_type_ids:he=null}={}){const{tokens:Ce,token_type_ids:We}=this._tokenize_helper(j,{pair:te,add_special_tokens:de}),qe=this.model.convert_tokens_to_ids(Ce),Ke={input_ids:qe,attention_mask:new Array(qe.length).fill(1)};return(he??this.return_token_type_ids)&&We&&(Ke.token_type_ids=We),Ke}_tokenize_helper(j,{pair:te=null,add_special_tokens:de=!1}={}){const he=this._encode_text(j),Ce=this._encode_text(te);return this.post_processor?this.post_processor(he,Ce,{add_special_tokens:de}):{tokens:(0,i.mergeArrays)(he??[],Ce??[])}}tokenize(j,{pair:te=null,add_special_tokens:de=!1}={}){return this._tokenize_helper(j,{pair:te,add_special_tokens:de}).tokens}encode(j,{text_pair:te=null,add_special_tokens:de=!0,return_token_type_ids:he=null}={}){return this._encode_plus(j,{text_pair:te,add_special_tokens:de,return_token_type_ids:he}).input_ids}batch_decode(j,te={}){return j instanceof a.Tensor&&(j=j.tolist()),j.map(de=>this.decode(de,te))}decode(j,te={}){if(j instanceof a.Tensor&&(j=P(j)),!Array.isArray(j)||j.length===0||!(0,i.isIntegralNumber)(j[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(j,te)}decode_single(j,{skip_special_tokens:te=!1,clean_up_tokenization_spaces:de=null}){let he=this.model.convert_ids_to_tokens(j);te&&(he=he.filter(We=>!this.special_tokens.includes(We)));let Ce=this.decoder?this.decoder(he):he.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ce=Ce.replaceAll(this.decoder.end_of_word_suffix," "),te&&(Ce=Ce.trim())),(de??this.clean_up_tokenization_spaces)&&(Ce=A(Ce)),Ce}get_chat_template({chat_template:j=null,tools:te=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const de=this.chat_template;if(j!==null&&Object.hasOwn(de,j))j=de[j];else if(j===null)if(te!==null&&"tool_use"in de)j=de.tool_use;else if("default"in de)j=de.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(de).sort()}.`)}else if(j===null)if(this.chat_template)j=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return j}apply_chat_template(j,{tools:te=null,documents:de=null,chat_template:he=null,add_generation_prompt:Ce=!1,tokenize:We=!0,padding:qe=!1,truncation:Ke=!1,max_length:Ze=null,return_tensor:ht=!0,return_dict:Ct=!1,tokenizer_kwargs:kt={},...Wt}={}){if(he=this.get_chat_template({chat_template:he,tools:te}),typeof he!="string")throw Error(`chat_template must be a string, but got ${typeof he}`);let Ot=this._compiled_template_cache.get(he);Ot===void 0&&(Ot=new d.Template(he),this._compiled_template_cache.set(he,Ot));const Ut=Object.create(null);for(const _r of cs){const Yr=this.getToken(_r);Yr&&(Ut[_r]=Yr)}const vr=Ot.render({messages:j,add_generation_prompt:Ce,tools:te,documents:de,...Ut,...Wt});if(We){const _r=this._call(vr,{add_special_tokens:!1,padding:qe,truncation:Ke,max_length:Ze,return_tensor:ht,...kt});return Ct?_r:_r.input_ids}return vr}}class qr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ur extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class us extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class xs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ts extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Es extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ds extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class mr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Be extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class et extends dt{}class it extends dt{}class rr extends dt{constructor(j,te){super(j,te);re(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class zt extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class kr extends dt{}class ps extends dt{}class hs extends dt{}class Er extends dt{constructor(F,j){super(F,j),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)),this.lang_to_token=te=>te}_build_translation_inputs(F,j,te){return br(this,F,j,te)}}class ms extends Er{}class fs extends dt{}class Qr extends dt{}const Ps="▁";class qs extends dt{constructor(j,te){super(j,te);re(this,"padding_side","left");this.legacy=te.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new xt({replacement:Ps,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(j){if(j===null)return null;if(this.legacy||j.length===0)return super._encode_text(j);let te=super._encode_text(Ps+j.replaceAll(Ps," "));return te.length>1&&te[0]===Ps&&this.special_tokens.includes(te[1])&&(te=te.slice(1)),te}}class Qs extends dt{}class Xs extends dt{}class Js extends dt{}class _s extends dt{}class Ys extends dt{}class Zs extends dt{}class en extends dt{}class Lr extends dt{}class Cs extends dt{}function br(ue,F,j,te){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const de=te.src_lang,he=te.tgt_lang;if(!ue.language_codes.includes(he))throw new Error(`Target language code "${he}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(de!==void 0){if(!ue.language_codes.includes(de))throw new Error(`Source language code "${de}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const Ce of ue.post_processor.config.single)if("SpecialToken"in Ce&&ue.languageRegex.test(Ce.SpecialToken.id)){Ce.SpecialToken.id=ue.lang_to_token(de);break}}return te.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(he)])[0],ue._call(F,j)}class Ls extends dt{constructor(F,j){super(F,j),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)),this.lang_to_token=te=>te}_build_translation_inputs(F,j,te){return br(this,F,j,te)}}class zs extends dt{constructor(F,j){super(F,j),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)).map(te=>te.slice(2,-2)),this.lang_to_token=te=>`__${te}__`}_build_translation_inputs(F,j,te){return br(this,F,j,te)}}class Ir extends dt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(F,{return_timestamps:j=!1,return_language:te=!1,time_precision:de=null,force_full_sequences:he=!0}={}){if(de===null)throw Error("Must specify time_precision");let Ce=null;const We=j==="word";function qe(){return{language:Ce,timestamp:[null,null],text:""}}const Ke=[];let Ze=qe(),ht=0;const Ct=this.timestamp_begin,Wt=Ct+1500;let Ot=[],Ut=[],vr=!1,_r=null;const Yr=new Set(this.all_special_ids);for(const Gt of F){const Zt=Gt.tokens,gr=We?Gt.token_timestamps:null;let Zr=null,ws=Ct;if("stride"in Gt){const[Rt,Jt,qt]=Gt.stride;if(ht-=Jt,_r=Rt-qt,Jt&&(ws=Jt/de+Ct),qt)for(let er=Zt.length-1;er>=0;--er){const ir=Number(Zt[er]);if(ir>=Ct){if(Zr!==null&&(ir-Ct)*de<_r)break;Zr=ir}}}let Ht=[],ur=[];for(let Rt=0;Rt=Ct&&Jt<=Wt){const qt=(Jt-Ct)*de+ht,er=(0,o.round)(qt,2);if(Zr!==null&&Jt>=Zr)vr=!0;else if(vr||Ot.length>0&&Jt0?(Ot.push(Ht),We&&Ut.push(ur)):Ot.every(Rt=>Rt.length===0)&&(Ze=qe(),Ot=[],Ht=[],Ut=[],ur=[])}if(Ot.length>0){if(he&&j)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Gt,Zt]=this.findLongestCommonSequence(Ot,Ut),gr=this.decode(Gt);Ze.text=gr,We&&(Ze.words=this.collateWordTimestamps(Gt,Zt,Ce)),Ke.push(Ze)}let xr=Object.create(null);const gs=Ke.map(Gt=>Gt.text).join("");if(j||te){for(let Gt=0;Gt0;let We=Ce?[]:null,qe=Ce?j[0]:null;for(let Ke=1;KeJt===ws[qt]&&qe[gs+qt]<=j[Ke][gr+qt]).length:Ht=Zt.filter((Jt,qt)=>Jt===ws[qt]).length;const ur=xr/1e4,Rt=Ht/xr+ur;Ht>1&&Rt>ht&&(ht=Rt,Ct=[gs,Gt,gr,Zr])}const[Wt,Ot,Ut,vr]=Ct,_r=Math.floor((Ot+Wt)/2),Yr=Math.floor((vr+Ut)/2);he.push(...te.slice(0,_r)),te=Ze.slice(Yr),de=te.length,Ce&&(We.push(...qe.slice(0,_r)),qe=j[Ke].slice(Yr))}return he.push(...te),Ce?(We.push(...qe),[he,We]):[he,[]]}collateWordTimestamps(F,j,te){const[de,he,Ce]=this.combineTokensIntoWords(F,te),We=[];for(let qe=0;qe=de){const We=((Ce-de)*te).toFixed(2);he.push(`<|${We}|>`),he.push([])}else he[he.length-1].push(Ce);return he=he.map(Ce=>typeof Ce=="string"?Ce:super.decode(Ce,j)),he.join("")}splitTokensOnUnicode(F){const j=this.decode(F,{decode_with_timestamps:!0}),te="�",de=[],he=[],Ce=[];let We=[],qe=[],Ke=0;for(let Ze=0;Ze=this.model.tokens_to_ids.get("<|endoftext|>"),Wt=Ze.startsWith(" "),Ot=Ze.trim(),Ut=qe.test(Ot);if(kt||Wt||Ut||he.length===0)he.push(Ze),Ce.push(ht),We.push(Ct);else{const vr=he.length-1;he[vr]+=Ze,Ce[vr].push(...ht),We[vr].push(...Ct)}}return[he,Ce,We]}mergePunctuations(F,j,te,de,he){const Ce=structuredClone(F),We=structuredClone(j),qe=structuredClone(te);let Ke=Ce.length-2,Ze=Ce.length-1;for(;Ke>=0;)Ce[Ke].startsWith(" ")&&de.includes(Ce[Ke].trim())?(Ce[Ze]=Ce[Ke]+Ce[Ze],We[Ze]=(0,i.mergeArrays)(We[Ke],We[Ze]),qe[Ze]=(0,i.mergeArrays)(qe[Ke],qe[Ze]),Ce[Ke]="",We[Ke]=[],qe[Ke]=[]):Ze=Ke,--Ke;for(Ke=0,Ze=1;Zeht),We.filter(ht=>ht.length>0),qe.filter(ht=>ht.length>0)]}}class Xr extends dt{}class Tn extends dt{}class zr extends dt{}class En extends dt{constructor(F,j){super(F,j),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(te=>this.languageRegex.test(te)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(F){if(F===null)return null;const[j,...te]=F.trim().split(this.languageRegex);if(te.length===0)return super._encode_text(j);if(te.length===2){const[de,he]=te;return this.supported_language_codes.includes(de)||console.warn(`Unsupported language code "${de}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,i.mergeArrays)([de],super._encode_text(he))}}}class Bs extends dt{}class Ar extends dt{}class Jr extends dt{}class cr extends dt{}class fr extends dt{}class Rs extends dt{constructor(F,j){super(F,j),this.decoder=new ct({})}}class Pn extends dt{}class Ss extends dt{}class Cn{static async from_pretrained(F,{progress_callback:j=null,config:te=null,cache_dir:de=null,local_files_only:he=!1,revision:Ce="main",legacy:We=null}={}){var Ct;const[qe,Ke]=await u(F,{progress_callback:j,config:te,cache_dir:de,local_files_only:he,revision:Ce,legacy:We}),Ze=((Ct=Ke.tokenizer_class)==null?void 0:Ct.replace(/Fast$/,""))??"PreTrainedTokenizer";let ht=this.TOKENIZER_CLASS_MAPPING[Ze];return ht||(console.warn(`Unknown tokenizer class "${Ze}", attempting to construct from base class.`),ht=dt),new ht(qe,Ke)}}re(Cn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:kr,DistilBertTokenizer:et,CamembertTokenizer:it,DebertaTokenizer:Ts,DebertaV2Tokenizer:Es,BertTokenizer:qr,HerbertTokenizer:Ds,ConvBertTokenizer:mr,RoFormerTokenizer:Be,XLMTokenizer:rr,ElectraTokenizer:zt,MobileBertTokenizer:us,SqueezeBertTokenizer:xs,AlbertTokenizer:Ur,GPT2Tokenizer:ps,BartTokenizer:hs,MBartTokenizer:Er,MBart50Tokenizer:ms,RobertaTokenizer:fs,WhisperTokenizer:Ir,CodeGenTokenizer:Xr,CLIPTokenizer:Tn,SiglipTokenizer:zr,MarianTokenizer:En,BloomTokenizer:Qr,NllbTokenizer:Ls,M2M100Tokenizer:zs,LlamaTokenizer:qs,CodeLlamaTokenizer:Qs,XLMRobertaTokenizer:Xs,MPNetTokenizer:Js,FalconTokenizer:_s,GPTNeoXTokenizer:Ys,EsmTokenizer:Zs,Wav2Vec2CTCTokenizer:Bs,BlenderbotTokenizer:Ar,BlenderbotSmallTokenizer:Jr,SpeechT5Tokenizer:cr,NougatTokenizer:fr,VitsTokenizer:Rs,Qwen2Tokenizer:en,GemmaTokenizer:Lr,Grok1Tokenizer:Cs,CohereTokenizer:Pn,MgpstrTokenizer:Ss,PreTrainedTokenizer:dt})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>h,hanning:()=>u,mel_filter_bank:()=>S,read_audio:()=>d,spectrogram:()=>k,window_function:()=>B});var s=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),o=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function d(V,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(V)).arrayBuffer(),Q=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${Q.sampleRate}Hz.`);const ie=await Q.decodeAudioData(H);let le;if(ie.numberOfChannels===2){const ae=Math.sqrt(2),ge=ie.getChannelData(0),N=ie.getChannelData(1);le=new Float32Array(ge.length);for(let O=0;O2595*Math.log10(1+V/700),kaldi:V=>1127*Math.log(1+V/700),slaney:(V,Y=1e3,H=15,Q=27/Math.log(6.4))=>V>=Y?H+Math.log(V/Y)*Q:3*V/200};function _(V,Y="htk"){const H=w[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?H(V):V.map(Q=>H(Q))}const P={htk:V=>700*(10**(V/2595)-1),kaldi:V=>700*(Math.exp(V/1127)-1),slaney:(V,Y=1e3,H=15,Q=Math.log(6.4)/27)=>V>=H?Y*Math.exp(Q*(V-H)):200*V/3};function A(V,Y="htk"){const H=P[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?H(V):V.map(Q=>H(Q))}function v(V,Y){const H=Float64Array.from({length:Y.length-1},(ae,ge)=>Y[ge+1]-Y[ge]),Q=Array.from({length:V.length},()=>new Array(Y.length));for(let ae=0;aenew Array(V.length));for(let ae=0;aeV+Q*le)}function S(V,Y,H,Q,ie,le=null,ae="htk",ge=!1){if(le!==null&&le!=="slaney")throw new Error('norm must be one of null or "slaney"');const N=_(H,ae),O=_(Q,ae),G=y(N,O,Y+2);let ne=A(G,ae),X;if(ge){const fe=ie/(V*2);X=_(Float64Array.from({length:V},(ke,He)=>He*fe),ae),ne=G}else X=y(0,Math.floor(ie/2),V);const we=v(X,ne);if(le!==null&&le==="slaney")for(let fe=0;feie)throw Error(`frame_length (${H}) may not be larger than fft_length (${ie})`);if(Pe!==H)throw new Error(`Length of the window (${Pe}) must equal frame_length (${H})`);if(Q<=0)throw new Error("hop_length must be greater than zero");if(le===null&&G!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(ae){if(ge!=="reflect")throw new Error(`pad_mode="${ge}" not implemented yet.`);const be=Math.floor((ie-1)/2)+1;V=x(V,be,be)}let Ee=Math.floor(1+Math.floor((V.length-H)/Q));Me!==null&&EeEe?U&&(Le=K):Le=Ie=K);const Ne=new i.FFT(ie),Ve=new Float64Array(ie),D=new Float64Array(Ne.outputBufferSize),Z=new Float32Array(Fe*Le);for(let be=0;be=1;--Ae)Ve[Ae]-=O*Ve[Ae-1];Ve[0]*=1-O}for(let Ae=0;AeMath.pow(ge,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(H&&(ae=ae.subarray(0,V)),Q===null)return ae;if(V>Q)throw new Error(`Length of the window (${V}) may not be larger than frame_length (${Q})`);return ae}function R(V,Y){let H=44;const Q=new ArrayBuffer(H+V.length*4),ie=new DataView(Q);J(ie,0,"RIFF"),ie.setUint32(4,36+V.length*4,!0),J(ie,8,"WAVE"),J(ie,12,"fmt "),ie.setUint32(16,16,!0),ie.setUint16(20,3,!0),ie.setUint16(22,1,!0),ie.setUint32(24,Y,!0),ie.setUint32(28,Y*4,!0),ie.setUint16(32,4,!0),ie.setUint16(34,32,!0),J(ie,36,"data"),ie.setUint32(40,V.length*4,!0);for(let le=0;le{let le=await ie.arrayBuffer();a.writeFileSync(Q,Buffer.from(le))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Y,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>i,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>d,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>o,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",i="config.json",n="preprocessor_config.json",o=n,a="processor_config.json",l="chat_template.json",d="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>d,calculateReflectOffset:()=>w,count:()=>v,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>o,len:()=>A,mergeArrays:()=>u,pick:()=>P,pop:()=>p,product:()=>h,reverseDictionary:()=>i,saveBlob:()=>_});function s(y,S){y&&y(S)}function i(y){return Object.fromEntries(Object.entries(y).map(([S,x])=>[x,S]))}function n(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function o(y){var S,x,g;return((g=(x=(S=y==null?void 0:y.prototype)==null?void 0:S.__proto__)==null?void 0:x.constructor)==null?void 0:g.name)==="TypedArray"}function a(y){return Number.isInteger(y)||typeof y=="bigint"}function l(y){return y==null||y===-1}function d(y){const S=[];let x=y;for(;Array.isArray(x);)S.push(x.length),x=x[0];return S}function p(y,S,x=void 0){const g=y[S];if(g!==void 0)return delete y[S],g;if(x===void 0)throw Error(`Key ${S} does not exist in object.`);return x}function u(...y){return Array.prototype.concat.apply([],y)}function h(...y){return y.reduce((S,x)=>S.flatMap(g=>x.map(M=>[g,M])))}function w(y,S){return Math.abs((y+S)%(2*S)-S)}function _(y,S){const x=URL.createObjectURL(S),g=document.createElement("a");g.href=x,g.download=y,g.click(),g.remove(),URL.revokeObjectURL(x)}function P(y,S){return Object.assign({},...S.map(x=>{if(y[x]!==void 0)return{[x]:y[x]}}))}function A(y){let S=0;for(const x of y)++S;return S}function v(y,S){let x=0;for(const g of y)g===S&&++x;return x}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>i,PriorityQueue:()=>s,TokenLattice:()=>o});class s{constructor(d=(u,h)=>u>h,p=1/0){this._heap=[],this._comparator=d,this._maxSize=p}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const p of d)if(this.size0&&this._swap(0,p),this._heap.pop(),this._siftDown(),d}replace(d){const p=this.peek();return this._heap[0]=d,this._siftDown(),p}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,p){return this._comparator(this._heap[d],this._heap[p])}_swap(d,p){const u=this._heap[d];this._heap[d]=this._heap[p],this._heap[p]=u}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const h=new a(this.bosTokenId,0,0,0,0),w=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(h.clone()),this.nodes.push(w.clone()),this.beginNodes[this.len].push(w),this.endNodes[0].push(h)}insert(d,p,u,h){const w=this.nodes.length,_=new a(h,w,d,p,u);this.beginNodes[d].push(_),this.endNodes[d+p].push(_),this.nodes.push(_)}viterbi(){const d=this.len;let p=0;for(;p<=d;){if(this.beginNodes[p].length==0)return[];for(let P of this.beginNodes[p]){P.prev=null;let A=0,v=null;for(let y of this.endNodes[p]){const S=y.backtraceScore+P.score;(v===null||S>A)&&(v=y.clone(),A=S)}if(v!==null)P.prev=v,P.backtraceScore=A;else return[]}++p}const u=[],w=this.beginNodes[d][0].prev;if(w===null)return[];let _=w.clone();for(;_.prev!==null;)u.push(_.clone()),_=_.clone().prev.clone();return u.reverse(),u}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(p=>this.piece(p))}tokenIds(){return this.viterbi().map(p=>p.tokenId)}}class a{constructor(d,p,u,h,w){this.tokenId=d,this.nodeId=p,this.pos=u,this.length=h,this.score=w,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>o,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),i=t("./src/utils/devices.js");const n=function(){let d;return async function(){if(d===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)d=!1;else try{d=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{d=!1}return d}}(),o=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[i.DEVICE_TYPES.wasm]:o.q8}),l=Object.freeze({[o.fp32]:"",[o.fp16]:"_fp16",[o.int8]:"_int8",[o.uint8]:"_uint8",[o.q8]:"_quantized",[o.q4]:"_q4",[o.q4f16]:"_q4f16",[o.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let i=function(...n){return i._call(...n)};return Object.setPrototypeOf(i,new.target.prototype)}_call(...i){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>u,getModelFile:()=>A,getModelJSON:()=>v});var s=t("?7a2c"),i=t("?a42a"),n=t("./src/env.js"),o=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class d{constructor(g){if(this.filePath=g,this.headers=new Headers,this.exists=s.existsSync(g),this.exists){this.status=200,this.statusText="OK";let M=s.statSync(g);this.headers.set("content-length",M.size.toString()),this.updateContentType();const E=s.createReadStream(g);this.body=new ReadableStream({start(k){E.on("data",B=>k.enqueue(B)),E.on("end",()=>k.close()),E.on("error",B=>k.error(B))},cancel(){E.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const g=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[g]??"application/octet-stream")}clone(){let g=new d(this.filePath);return g.exists=this.exists,g.status=this.status,g.statusText=this.statusText,g.headers=new Headers(this.headers),g}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const g=await s.promises.readFile(this.filePath);return new Blob([g],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,g=null,M=null){let E;try{E=new URL(x)}catch{return!1}return!(g&&!g.includes(E.protocol)||M&&!M.includes(E.hostname))}async function u(x){var g;if(n.env.useFS&&!p(x,["http:","https:","blob:"]))return new d(x.toString());if(typeof process<"u"&&((g=process==null?void 0:process.release)==null?void 0:g.name)==="node"){const M=!!(As!=null&&As.TESTING_REMOTELY),E=n.env.version,k=new Headers;if(k.set("User-Agent",`transformers.js/${E}; is_ci/${M};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const R=(As==null?void 0:As.HF_TOKEN)??(As==null?void 0:As.HF_ACCESS_TOKEN);R&&k.set("Authorization",`Bearer ${R}`)}return fetch(x,{headers:k})}else return fetch(x)}const h={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function w(x,g,M){if(!M)return null;const E=h[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${E}: "${g}".`)}class _{constructor(g){this.path=g}async match(g){let M=i.join(this.path,g),E=new d(M);if(E.exists)return E}async put(g,M,E=void 0){let k=i.join(this.path,g);try{const B=M.headers.get("Content-Length"),R=parseInt(B??"0");let J=0;await s.promises.mkdir(i.dirname(k),{recursive:!0});const q=s.createWriteStream(k),V=M.body.getReader();for(;;){const{done:Y,value:H}=await V.read();if(Y)break;await new Promise((ie,le)=>{q.write(H,ae=>{if(ae){le(ae);return}ie()})}),J+=H.length;const Q=R?J/R*100:0;E==null||E({progress:Q,loaded:J,total:R})}q.close()}catch(B){try{await s.promises.unlink(k)}catch{}throw B}}}async function P(x,...g){for(let M of g)try{let E=await x.match(M);if(E)return E}catch{continue}}async function A(x,g,M=!0,E={},k=!1){if(!n.env.allowLocalModels){if(E.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,o.dispatchCallback)(E.progress_callback,{status:"initiate",name:x,file:g});let B;if(!B&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{B=await caches.open("transformers-cache")}catch(G){console.warn("An error occurred while opening the browser cache:",G)}}if(!B&&n.env.useFSCache&&(B=new _(E.cache_dir??n.env.cacheDir)),!B&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");B=n.env.customCache}const R=E.revision??"main";let J=S(x,g),q=S(n.env.localModelPath,J),V=J,Y=S(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(R)),g),H=R==="main"?J:S(x,R,g),Q,ie=B instanceof _?H:Y,le=!1,ae;B&&(ae=await P(B,q,ie));const ge=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(J,["http:","https:"])){if(E.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${V}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${V}.`)}else try{ae=await u(V),Q=V}catch(ne){console.warn(`Unable to load from local path "${V}": "${ne}"`)}if(ae===void 0||ae.status===404){if(E.local_files_only||!n.env.allowRemoteModels){if(M)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${V}".`);return null}if(ae=await u(Y),ae.status!==200)return w(ae.status,Y,M);Q=ie}le=B&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,o.dispatchCallback)(E.progress_callback,{status:"download",name:x,file:g});let N;if(!(n.apis.IS_NODE_ENV&&k)){let G;E.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(G=new Uint8Array(await ae.arrayBuffer()),(0,o.dispatchCallback)(E.progress_callback,{status:"progress",name:x,file:g,progress:100,loaded:G.length,total:G.length})):G=await y(ae,ne=>{(0,o.dispatchCallback)(E.progress_callback,{status:"progress",name:x,file:g,...ne})}):G=new Uint8Array(await ae.arrayBuffer()),N=G}if(le&&Q&&await B.match(Q)===void 0&&(N?await B.put(Q,new Response(N,{headers:ae.headers})).catch(G=>{console.warn(`Unable to add response to browser cache: ${G}.`)}):await B.put(Q,ae,E.progress_callback)),(0,o.dispatchCallback)(E.progress_callback,{status:"done",name:x,file:g}),N){if(k)throw new Error("Cannot return path in a browser environment.");return N}if(ae instanceof d)return ae.filePath;const O=await B.match(Q);if(O instanceof d)return O.filePath;throw new Error("Unable to return path for response.")}async function v(x,g,M=!0,E={}){const k=await A(x,g,M,E,!1);if(k===null)return{};const R=new TextDecoder("utf-8").decode(k);return JSON.parse(R)}async function y(x,g){const M=x.headers.get("Content-Length");M===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let E=parseInt(M??"0"),k=new Uint8Array(E),B=0;const R=x.body.getReader();async function J(){const{done:q,value:V}=await R.read();if(q)return;const Y=B+V.length;if(Y>E){E=Y;const Q=new Uint8Array(E);Q.set(k),k=Q}k.set(V,B),B=Y;const H=B/E*100;return g({progress:H,loaded:B,total:E}),J()}return await J(),k}function S(...x){return x=x.map((g,M)=>(M&&(g=g.replace(new RegExp("^/"),"")),M!==x.length-1&&(g=g.replace(new RegExp("/$"),"")),g)),x.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>P});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js"),n=t("./src/env.js"),o=t("./src/utils/tensor.js"),a=t("?2b25");let l,d,p;const u=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(u)l=(A,v)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(A,v)},p=self.createImageBitmap,d=self.ImageData;else if(a)p=async A=>{const y=(await A.metadata()).channels,{data:S,info:x}=await A.rotate().raw().toBuffer({resolveWithObject:!0}),g=new _(new Uint8ClampedArray(S),x.width,x.height,x.channels);return y!==void 0&&y!==x.channels&&g.convert(y),g};else throw new Error("Unable to load image processing library.");const h={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},w=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(v,y,S,x){this.data=v,this.width=y,this.height=S,this.channels=x}get size(){return[this.width,this.height]}static async read(v){if(v instanceof _)return v;if(typeof v=="string"||v instanceof URL)return await this.fromURL(v);throw new Error(`Unsupported input type: ${typeof v}`)}static fromCanvas(v){if(!u)throw new Error("fromCanvas() is only supported in browser environments.");const S=v.getContext("2d").getImageData(0,0,v.width,v.height).data;return new _(S,v.width,v.height,4)}static async fromURL(v){const y=await(0,i.getFile)(v);if(y.status!==200)throw new Error(`Unable to read image from "${v}" (${y.status} ${y.statusText})`);const S=await y.blob();return this.fromBlob(S)}static async fromBlob(v){if(u){const y=await p(v),S=l(y.width,y.height).getContext("2d");return S.drawImage(y,0,0),new this(S.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=a(await v.arrayBuffer());return await p(y)}}static fromTensor(v,y="CHW"){if(v.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${v.dims.length} dimensions.`);if(y==="CHW")v=v.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(v.data instanceof Uint8ClampedArray||v.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${v.type}`);switch(v.dims[2]){case 1:case 2:case 3:case 4:return new _(v.data,v.dims[1],v.dims[0],v.dims[2]);default:throw new Error(`Unsupported number of channels: ${v.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const v=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,S=0;y=0?k=S:R=-S,x>=0?B=x:J=-x,E.drawImage(M,k,B,v,y,R,J,v,y),new _(E.getImageData(0,0,v,y).data,v,y,4).convert(g)}else{let g=this.toSharp();if(S>=0&&x>=0)g=g.extract({left:Math.floor(S),top:Math.floor(x),width:v,height:y});else if(S<=0&&x<=0){const M=Math.floor(-x),E=Math.floor(-S);g=g.extend({top:M,left:E,right:v-this.width-E,bottom:y-this.height-M})}else{let M=[0,0],E=0;x<0?(M[0]=Math.floor(-x),M[1]=y-this.height-M[0]):E=Math.floor(x);let k=[0,0],B=0;S<0?(k[0]=Math.floor(-S),k[1]=v-this.width-k[0]):B=Math.floor(S),g=g.extend({top:M[0],bottom:M[1],left:k[0],right:k[1]}).extract({left:B,top:E,width:v,height:y})}return await p(g)}}async toBlob(v="image/png",y=1){if(!u)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:v,quality:y})}toTensor(v="CHW"){let y=new o.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(v!=="HWC")if(v==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${v}`);return y}toCanvas(){if(!u)throw new Error("toCanvas() is only supported in browser environments.");const v=this.clone().rgba(),y=l(v.width,v.height),S=new d(v.data,v.width,v.height);return y.getContext("2d").putImageData(S,0,0),y}split(){const{data:v,width:y,height:S,channels:x}=this,g=v.constructor,M=v.length/x,E=Array.from({length:x},()=>new g(M));for(let k=0;knew _(k,y,S,1))}_update(v,y,S,x=null){return this.data=v,this.width=y,this.height=S,x!==null&&(this.channels=x),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(v){if(this.channels===v)return this;switch(v){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(v){if(u){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const y=v.split(".").pop().toLowerCase(),S=w.get(y)??"image/png",x=await this.toBlob(S);(0,s.saveBlob)(v,x)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(v);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(u)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const P=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>P,bankers_round:()=>y,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>o,magnitude:()=>d,max:()=>u,medianFilter:()=>A,min:()=>p,permute_data:()=>i,round:()=>v,softmax:()=>n});function s(x,[g,M,E],[k,B],R="bilinear",J=!1){const q=B/E,V=k/M,Y=new x.constructor(k*B*g),H=M*E,Q=k*B;for(let ie=0;ie=0;--J)k[J]=q,E[J]=g[M[J]],q*=E[J];const B=M.map((J,q)=>k[M.indexOf(q)]),R=new x.constructor(x.length);for(let J=0;J=0;--V)q+=Y%g[V]*B[V],Y=Math.floor(Y/g[V]);R[q]=x[J]}return[R,E]}function n(x){const g=u(x)[0],M=x.map(B=>Math.exp(B-g)),E=M.reduce((B,R)=>B+R,0);return M.map(B=>B/E)}function o(x){const g=u(x)[0];let M=0;for(let B=0;BB-g-E)}function a(x,g){let M=0;for(let E=0;Eg+M*M,0))}function p(x){if(x.length===0)throw Error("Array must not be empty");let g=x[0],M=0;for(let E=1;Eg&&(g=x[E],M=E);return[g,M]}function h(x){return x>0&&(x&x-1)===0}class w{constructor(g){if(this.size=g|0,this.size<=1||!h(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=g<<1,this.table=new Float64Array(this.size*2);for(let E=0;EE;E<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=g[k];return E}toComplexArray(g,M){const E=M||this.createComplexArray();for(let k=0;k>>1],E[k+1]=0;return E}transform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._transform4(g,M,1)}realTransform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._realTransform4(g,M,1)}inverseTransform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._transform4(g,M,-1);for(let E=0;E>=2;R>=2;R>>=2){J=k/R<<1;const Q=J>>>2;for(q=0;q>>1,R>>>1)}else for(q=0,V=0;q>>1,R>>>1,E)}const H=this.table;for(R>>=2;R>=2;R>>=2){J=k/R<<1;const ie=J>>>1,le=ie>>>1,ae=le>>>1;for(q=0;q>>1;for(let ie=2;ie>1;++Y){const H=(Y+1-g)**2/2,Q=Math.sqrt(q**2+V**2)**H,ie=H*Math.atan2(V,q),le=2*Y;B[le]=Q*Math.cos(ie),B[le+1]=Q*Math.sin(ie),R[le]=B[le],R[le+1]=-B[le+1]}this._slicedChirpBuffer=B.subarray(M,E),this._f=new w(k>>1),this._f.transform(this._chirpBuffer,R)}_transform(g,M,E){const k=this._buffer1,B=this._buffer2,R=this._outBuffer1,J=this._outBuffer2,q=this._chirpBuffer,V=this._slicedChirpBuffer,Y=this._a;if(E)for(let H=0;H>1,le=M[ie];k[H]=le*V[H],k[Q]=le*V[Q]}else for(let H=0;H=x.length&&(q=2*(x.length-1)-q),E[R++]=x[q]}E.sort(),M[B]=E[k]}return M}function v(x,g){const M=Math.pow(10,g);return Math.round(x*M)/M}function y(x){const g=Math.round(x);return Math.abs(x)%1===.5?g%2===0?g:g-1:g}function S(x){const g=x.length,M=x[0].length,E=[g+1,M+1],k=Array.from({length:E[0]},()=>Array(E[1]).fill(1/0));k[0][0]=0;const B=Array.from({length:E[0]},()=>Array(E[1]).fill(-1));for(let Y=1;Y0||J>0;)switch(q.push(R-1),V.push(J-1),B[R][J]){case 0:--R,--J;break;case 1:--R;break;case 2:--J;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${R}, ${J}]. Please file a bug report.`)}return q.reverse(),V.reverse(),[q,V]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>o,Tensor:()=>a,cat:()=>M,full:()=>V,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>u,layer_norm:()=>y,matmul:()=>h,mean:()=>R,mean_pooling:()=>v,ones:()=>H,ones_like:()=>Q,permute:()=>d,quantize_embeddings:()=>ge,rand:()=>ae,rfft:()=>w,slice:()=>A,stack:()=>E,std_mean:()=>B,topk:()=>_,zeros:()=>ie,zeros_like:()=>le});var s=t("./src/utils/maths.js"),i=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const o=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...O){re(this,"ort_tensor");return(0,i.isONNXTensor)(O[0])?this.ort_tensor=O[0]:this.ort_tensor=new i.Tensor(O[0],O[1],O[2]),new Proxy(this,{get:(G,ne)=>{if(typeof ne=="string"){let X=Number(ne);if(Number.isInteger(X))return G._getitem(X)}return G[ne]},set:(G,ne,X)=>G[ne]=X})}get dims(){return this.ort_tensor.dims}set dims(O){this.ort_tensor.dims=O}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[O,...G]=this.dims;if(G.length>0){const ne=G.reduce((X,we)=>X*we);for(let X=0;X0){const X=ne.reduce((we,fe)=>we*fe);return this._subarray(O,X,ne)}else return new a(this.type,[this.data[O]],ne)}indexOf(O){const G=this.data;for(let ne=0;nepe)throw new Error(`Invalid slice: ${K}`);const Pe=[Math.max(U,0),Math.min(pe,this.dims[Me])];ne.push(Pe),G.push(Pe[1]-Pe[0])}else throw new Error(`Invalid slice: ${K}`)}const X=ne.map(([Me,K])=>K-Me),we=X.reduce((Me,K)=>Me*K),fe=this.data,ke=new fe.constructor(we),He=this.stride();for(let Me=0;Me=0;--U){const Pe=X[U];K+=(pe%Pe+ne[U][0])*He[U],pe=Math.floor(pe/Pe)}ke[Me]=fe[K]}return new a(this.type,ke,G)}permute(...O){return d(this,O)}transpose(...O){return this.permute(...O)}sum(O=null,G=!1){return this.norm(1,O,G)}norm(O="fro",G=null,ne=!1){if(O==="fro")O=2;else if(typeof O=="string")throw Error(`Unsupported norm: ${O}`);const X=this.data,we=(Me,K)=>Me+K**O;if(G===null){const Me=X.reduce(we,0)**(1/O);return new a(this.type,[Me],[])}const[fe,ke,He]=k(we,this,G,ne);if(O!==1)for(let Me=0;Me=0;--He){const U=this.dims[He];if(He!==G){const pe=Me%U;ke+=pe*K,K*=this.dims[He]}Me=Math.floor(Me/U)}X[fe]/=we[ke]}return this}normalize(O=2,G=1){return this.clone().normalize_(O,G)}stride(){return J(this.dims)}squeeze(O=null){return new a(this.type,this.data,S(this.dims,O))}squeeze_(O=null){return this.dims=S(this.dims,O),this}unsqueeze(O=null){return new a(this.type,this.data,x(this.dims,O))}unsqueeze_(O=null){return this.dims=x(this.dims,O),this}flatten_(O=0,G=-1){G=(G+this.dims.length)%this.dims.length;let ne=this.dims.slice(0,O),X=this.dims.slice(O,G+1),we=this.dims.slice(G+1);return this.dims=[...ne,X.reduce((fe,ke)=>fe*ke,1),...we],this}flatten(O=0,G=-1){return this.clone().flatten_(O,G)}view(...O){let G=-1;for(let X=0;Xke!==G?we*fe:we,1);O[G]=ne.length/X}return new a(this.type,ne,O)}neg_(){const O=this.data;for(let G=0;GO?1:0;return new a("bool",G,this.dims)}lt(O){const G=new Uint8Array(this.data.length),ne=this.data;for(let X=0;XMath.min(fe,ke),this,O,G,1/0);return new a(ne,X,we)}max(O=null,G=!1){if(O===null){const fe=(0,s.max)(this.data)[0];return new a(this.type,[fe],[])}const[ne,X,we]=k((fe,ke)=>Math.max(fe,ke),this,O,G,-1/0);return new a(ne,X,we)}argmin(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const ne=(0,s.min)(this.data)[1];return new a("int64",[BigInt(ne)],[])}argmax(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const ne=(0,s.max)(this.data)[1];return new a("int64",[BigInt(ne)],[])}to(O){if(this.type===O)return this;if(!o.hasOwnProperty(O))throw new Error(`Unsupported type: ${O}`);let G;const ne=["int64","uint64"].includes(this.type),X=["int64","uint64"].includes(O);return ne&&!X?G=Number:!ne&&X&&(G=BigInt),new a(O,o[O].from(this.data,G),this.dims)}}function l(N,O){const G=N.length,ne=O.reduce((we,fe)=>we*fe);if(G!==ne)throw Error(`cannot reshape array of size ${G} into shape (${O})`);let X=N;for(let we=O.length-1;we>=0;we--)X=X.reduce((fe,ke)=>{let He=fe[fe.length-1];return He.lengthnew a("int64",N,[N.length]);async function A(N,O,G,ne,X){return await(await n.TensorOpRegistry.slice)({x:N,s:P(O),e:P(G),a:P(ne),t:P(X??new Array(ne.length).fill(1))})}function v(N,O){const G=N.data,ne=O.data,X=[N.dims[0],N.dims[2]],we=new G.constructor(X[0]*X[1]),[fe,ke,He]=N.dims;let Me=0;for(let K=0;KG!==1):typeof O=="number"?N[O]===1&&N.splice(O,1):Array.isArray(O)&&(N=N.filter((G,ne)=>G!==1||!O.includes(ne))),N}function x(N,O){return O=g(O,N.length+1),N=N.slice(),N.splice(O,0,1),N}function g(N,O,G=null,ne=!0){if(ne&&(N<-O||N>=O))throw new Error(`IndexError: index ${N} is out of bounds for dimension${G===null?"":" "+G} with size ${O}`);return N<0&&(N=(N%O+O)%O),N}function M(N,O=0){O=g(O,N[0].dims.length);const G=N[0].dims.slice();G[O]=N.reduce((fe,ke)=>fe+ke.dims[O],0);const ne=G.reduce((fe,ke)=>fe*ke,1),X=new N[0].data.constructor(ne),we=N[0].type;if(O===0){let fe=0;for(const ke of N){const He=ke.data;X.set(He,fe),fe+=He.length}}else{let fe=0;for(let ke=0;ke=0;--pe){const Fe=Me[pe];let Ie=Pe%Fe;pe===O&&(Ie+=fe),U+=Ie*Ee,Ee*=G[pe],Pe=Math.floor(Pe/Fe)}X[U]=He[K]}fe+=Me[O]}}return new a(we,X,G)}function E(N,O=0){return M(N.map(G=>G.unsqueeze(O)),O)}function k(N,O,G=null,ne=!1,X=null){const we=O.data,fe=O.dims;G=g(G,fe.length);const ke=fe.slice();ke[G]=1;const He=new we.constructor(we.length/fe[G]);X!==null&&He.fill(X);for(let Me=0;Me=0;--U){const Ee=fe[U];if(U!==G){const Fe=pe%Ee;K+=Fe*Pe,Pe*=ke[U]}pe=Math.floor(pe/Ee)}He[K]=N(He[K],we[Me],Me,K)}return ne||ke.splice(G,1),[O.type,He,ke]}function B(N,O=null,G=1,ne=!1){const X=N.data,we=N.dims;if(O===null){const Pe=X.reduce((Le,Ne)=>Le+Ne,0)/X.length,Ee=Math.sqrt(X.reduce((Le,Ne)=>Le+(Ne-Pe)**2,0)/(X.length-G)),Fe=new a(N.type,[Pe],[]);return[new a(N.type,[Ee],[]),Fe]}O=g(O,we.length);const fe=R(N,O,ne),ke=fe.data,[He,Me,K]=k((pe,Pe,Ee,Fe)=>pe+(Pe-ke[Fe])**2,N,O,ne);for(let pe=0;peMe+K,0);return new a(N.type,[He/X.length],[])}O=g(O,ne.length);const[we,fe,ke]=k((He,Me)=>He+Me,N,O,G);if(ne[O]!==1)for(let He=0;He=0;--G)O[G]=ne,ne*=N[G];return O}function q(N,O,G,ne){const X=N.reduce((we,fe)=>we*fe,1);return new a(G,new ne(X).fill(O),N)}function V(N,O){let G,ne;if(typeof O=="number")G="float32",ne=Float32Array;else if(typeof O=="bigint")G="int64",ne=BigInt64Array;else if(typeof O=="boolean")G="bool",ne=Uint8Array;else throw new Error(`Unsupported data type: ${typeof O}`);return q(N,O,G,ne)}function Y(N,O){return V(N.dims,O)}function H(N){return q(N,1n,"int64",BigInt64Array)}function Q(N){return H(N.dims)}function ie(N){return q(N,0n,"int64",BigInt64Array)}function le(N){return ie(N.dims)}function ae(N){const O=N.reduce((G,ne)=>G*ne,1);return new a("float32",Float32Array.from({length:O},()=>Math.random()),N)}function ge(N,O){if(N.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(N.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(O))throw new Error("The precision must be either 'binary' or 'ubinary'");const G=O==="binary",ne=G?"int8":"uint8",X=G?Int8Array:Uint8Array,we=N.data,fe=new X(we.length/8);for(let ke=0;ke0?1:0,Me=Math.floor(ke/8),K=ke%8;fe[Me]|=He<<7-K,G&&K===0&&(fe[Me]-=128)}return new a(ne,fe,[N.dims[0],N.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>o,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),i=t("./src/env.js");class n{constructor(d,p){this.image=d,this.timestamp=p}}class o{constructor(d,p){d.length>0&&d[0]instanceof s.RawImage&&(d=d.map((u,h)=>new n(u,(h+1)/(d.length+1)*p))),this.frames=d,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:d=null,fps:p=null}={}){if(!i.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(d==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const u=[],h=document.createElement("video");if(h.crossOrigin="anonymous",h.muted=!0,typeof l=="string")h.src=l;else if(l instanceof Blob)h.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)h.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(S=>h.onloadedmetadata=S),h.seekable.start(0)===h.seekable.end(0)){const x=await(await fetch(h.src)).blob();h.src=URL.createObjectURL(x),await new Promise(g=>h.onloadedmetadata=g)}const w=h.duration;let _,P;d!=null?(_=d,P=d===1?0:w/(d-1)):(P=1/p,_=Math.floor(w/P));let A=[];for(let S=0;S<_;++S)A.push(d===1?w/2:S*P);const v=document.createElement("canvas");v.width=h.videoWidth,v.height=h.videoHeight;const y=v.getContext("2d",{willReadFrequently:!0});for(const S of A){h.currentTime=S,await new Promise(E=>{h.onseeked=E}),y.drawImage(h,0,0,v.width,v.height);const x=y.getImageData(0,0,v.width,v.height),g=new s.RawImage(x.data,v.width,v.height,4),M=new n(g,S);u.push(M)}return h.remove(),new o(u,w)}}},Kw={};function Ft(e){var r=Kw[e];if(r!==void 0)return r.exports;var t=Kw[e]={exports:{}};return Kv[e](t,t.exports,Ft),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Ft.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var i=Object.create(null);Ft.r(i);var n={};r=r||[null,e({}),e([]),e(e)];for(var o=s&2&&t;typeof o=="object"&&!~r.indexOf(o);o=e(o))Object.getOwnPropertyNames(o).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Ft.d(i,n),i}})(),Ft.d=(e,r)=>{for(var t in r)Ft.o(r,t)&&!Ft.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Ft.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Ft.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var f={};(()=>{/*!*****************************!*\ +`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${ee.value}`)}else if(z instanceof ye)switch(ee.value){case"abs":return new ye(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${ee.value}`)}else if(z instanceof He)switch(ee.value){case"items":return new K(Array.from(z.value.entries()).map(([ce,be])=>new K([new _e(ce),be])));case"length":return new ye(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ee.value}`)}throw new Error(`Cannot apply filter "${ee.value}" to type: ${z.type}`)}else if(D.filter.type==="CallExpression"){const ee=D.filter;if(ee.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ee.callee.type}`);const ce=ee.callee.value;if(ce==="tojson"){const[,be]=this.evaluateArguments(ee.args,Z),ve=be.get("indent")??new Pe;if(!(ve instanceof ye||ve instanceof Pe))throw new Error("If set, indent must be a number");return new _e(Ne(z,ve.value))}else if(ce==="join"){let be;if(z instanceof _e)be=Array.from(z.value);else if(z instanceof K)be=z.value.map(je=>je.value);else throw new Error(`Cannot apply filter "${ce}" to type: ${z.type}`);const[ve,Re]=this.evaluateArguments(ee.args,Z),Fe=ve.at(0)??Re.get("separator")??new _e("");if(!(Fe instanceof _e))throw new Error("separator must be a string");return new _e(be.join(Fe.value))}if(z instanceof K){switch(ce){case"selectattr":case"rejectattr":{const be=ce==="selectattr";if(z.value.some(Xe=>!(Xe instanceof He)))throw new Error(`\`${ce}\` can only be applied to array of objects`);if(ee.args.some(Xe=>Xe.type!=="StringLiteral"))throw new Error(`arguments of \`${ce}\` must be strings`);const[ve,Re,Fe]=ee.args.map(Xe=>this.evaluate(Xe,Z));let je;if(Re){const Xe=Z.tests.get(Re.value);if(!Xe)throw new Error(`Unknown test: ${Re.value}`);je=Xe}else je=(...Xe)=>Xe[0].__bool__().value;const Qe=z.value.filter(Xe=>{const ut=Xe.value.get(ve.value),wt=ut?je(ut,Fe):!1;return be?wt:!wt});return new K(Qe)}case"map":{const[,be]=this.evaluateArguments(ee.args,Z);if(be.has("attribute")){const ve=be.get("attribute");if(!(ve instanceof _e))throw new Error("attribute must be a string");const Re=be.get("default"),Fe=z.value.map(je=>{if(!(je instanceof He))throw new Error("items in map must be an object");return je.value.get(ve.value)??Re??new Te});return new K(Fe)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ce}`)}else if(z instanceof _e){switch(ce){case"indent":{const[be,ve]=this.evaluateArguments(ee.args,Z),Re=be.at(0)??ve.get("width")??new ye(4);if(!(Re instanceof ye))throw new Error("width must be a number");const Fe=be.at(1)??ve.get("first")??new ke(!1),je=be.at(2)??ve.get("blank")??new ke(!1),Qe=z.value.split(` +`),Xe=" ".repeat(Re.value),ut=Qe.map((wt,nr)=>!Fe.value&&nr===0||!je.value&&wt.length===0?wt:Xe+wt);return new _e(ut.join(` +`))}}throw new Error(`Unknown StringValue filter: ${ce}`)}else throw new Error(`Cannot apply filter "${ce}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${D.filter.type}`)}evaluateTestExpression(D,Z){const z=this.evaluate(D.operand,Z),ee=Z.tests.get(D.test.value);if(!ee)throw new Error(`Unknown test: ${D.test.value}`);const ce=ee(z);return new ke(D.negate?!ce:ce)}evaluateUnaryExpression(D,Z){const z=this.evaluate(D.argument,Z);switch(D.operator.value){case"not":return new ke(!z.value);default:throw new SyntaxError(`Unknown operator: ${D.operator.value}`)}}evalProgram(D,Z){return this.evaluateBlock(D.body,Z)}evaluateBlock(D,Z){let z="";for(const ee of D){const ce=this.evaluate(ee,Z);ce.type!=="NullValue"&&ce.type!=="UndefinedValue"&&(z+=ce.value)}return new _e(z)}evaluateIdentifier(D,Z){return Z.lookupVariable(D.value)}evaluateCallExpression(D,Z){const[z,ee]=this.evaluateArguments(D.args,Z);ee.size>0&&z.push(new Me(ee));const ce=this.evaluate(D.callee,Z);if(ce.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ce.type}`);return ce.value(z,Z)}evaluateSliceExpression(D,Z,z){if(!(D instanceof K||D instanceof _e))throw new Error("Slice object must be an array or string");const ee=this.evaluate(Z.start,z),ce=this.evaluate(Z.stop,z),be=this.evaluate(Z.step,z);if(!(ee instanceof ye||ee instanceof Te))throw new Error("Slice start must be numeric or undefined");if(!(ce instanceof ye||ce instanceof Te))throw new Error("Slice stop must be numeric or undefined");if(!(be instanceof ye||be instanceof Te))throw new Error("Slice step must be numeric or undefined");return D instanceof K?new K(G(D.value,ee.value,ce.value,be.value)):new _e(G(Array.from(D.value),ee.value,ce.value,be.value).join(""))}evaluateMemberExpression(D,Z){const z=this.evaluate(D.object,Z);let ee;if(D.computed){if(D.property.type==="SliceExpression")return this.evaluateSliceExpression(z,D.property,Z);ee=this.evaluate(D.property,Z)}else ee=new _e(D.property.value);let ce;if(z instanceof He){if(!(ee instanceof _e))throw new Error(`Cannot access property with non-string: got ${ee.type}`);ce=z.value.get(ee.value)??z.builtins.get(ee.value)}else if(z instanceof K||z instanceof _e)if(ee instanceof ye)ce=z.value.at(ee.value),z instanceof _e&&(ce=new _e(z.value.at(ee.value)));else if(ee instanceof _e)ce=z.builtins.get(ee.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ee.type}`);else{if(!(ee instanceof _e))throw new Error(`Cannot access property with non-string: got ${ee.type}`);ce=z.builtins.get(ee.value)}return ce instanceof X?ce:new Te}evaluateSet(D,Z){const z=this.evaluate(D.value,Z);if(D.assignee.type==="Identifier"){const ee=D.assignee.value;Z.setVariable(ee,z)}else if(D.assignee.type==="MemberExpression"){const ee=D.assignee,ce=this.evaluate(ee.object,Z);if(!(ce instanceof He))throw new Error("Cannot assign to member of non-object");if(ee.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ce.value.set(ee.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(D.assignee)}`);return new Pe}evaluateIf(D,Z){const z=this.evaluate(D.test,Z);return this.evaluateBlock(z.__bool__().value?D.body:D.alternate,Z)}evaluateFor(D,Z){const z=new Ae(Z);let ee,ce;if(D.iterable.type==="SelectExpression"){const je=D.iterable;ce=this.evaluate(je.iterable,z),ee=je.test}else ce=this.evaluate(D.iterable,z);if(!(ce instanceof K))throw new Error(`Expected iterable type in for loop: got ${ce.type}`);const be=[],ve=[];for(let je=0;jewt.setVariable(D.loopvar.value,Xe);else if(D.loopvar.type==="TupleLiteral"){const wt=D.loopvar;if(Xe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Xe.type}`);const nr=Xe;if(wt.value.length!==nr.value.length)throw new Error(`Too ${wt.value.length>nr.value.length?"few":"many"} items to unpack`);ut=jt=>{for(let dr=0;dr0?be[je-1]:new Te],["nextitem",je{var ve;const ce=new Ae(ee);z=z.slice();let be;((ve=z.at(-1))==null?void 0:ve.type)==="KeywordArgumentsValue"&&(be=z.pop());for(let Re=0;Rethis.evaluate(z,Z)));case"TupleLiteral":return new U(D.value.map(z=>this.evaluate(z,Z)));case"ObjectLiteral":{const z=new Map;for(const[ee,ce]of D.value){const be=this.evaluate(ee,Z);if(!(be instanceof _e))throw new Error(`Object keys must be strings: got ${be.type}`);z.set(be.value,this.evaluate(ce,Z))}return new He(z)}case"Identifier":return this.evaluateIdentifier(D,Z);case"CallExpression":return this.evaluateCallExpression(D,Z);case"MemberExpression":return this.evaluateMemberExpression(D,Z);case"UnaryExpression":return this.evaluateUnaryExpression(D,Z);case"BinaryExpression":return this.evaluateBinaryExpression(D,Z);case"FilterExpression":return this.evaluateFilterExpression(D,Z);case"TestExpression":return this.evaluateTestExpression(D,Z);default:throw new SyntaxError(`Unknown node type: ${D.type}`)}}};function Le(D){switch(typeof D){case"number":return new ye(D);case"string":return new _e(D);case"boolean":return new ke(D);case"undefined":return new Te;case"object":return D===null?new Pe:Array.isArray(D)?new K(D.map(Le)):new He(new Map(Object.entries(D).map(([Z,z])=>[Z,Le(z)])));case"function":return new pe((Z,z)=>{const ee=D(...Z.map(ce=>ce.value))??null;return Le(ee)});default:throw new Error(`Cannot convert to runtime value: ${D}`)}}function Ne(D,Z,z){const ee=z??0;switch(D.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(D.value);case"ArrayValue":case"ObjectValue":{const ce=Z?" ".repeat(Z):"",be=` +`+ce.repeat(ee),ve=be+ce;if(D.type==="ArrayValue"){const Re=D.value.map(Fe=>Ne(Fe,Z,ee+1));return Z?`[${ve}${Re.join(`,${ve}`)}${be}]`:`[${Re.join(", ")}]`}else{const Re=Array.from(D.value.entries()).map(([Fe,je])=>{const Qe=`"${Fe}": ${Ne(je,Z,ee+1)}`;return Z?`${ve}${Qe}`:Qe});return Z?`{${Re.join(",")}${be}}`:`{${Re.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${D.type}`)}}var Ve=class{constructor(D){re(this,"parsed");const Z=u(D,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=R(Z)}render(D){const Z=new Ae;if(Z.set("false",!1),Z.set("true",!0),Z.set("raise_exception",ce=>{throw new Error(ce)}),Z.set("range",O),D)for(const[ce,be]of Object.entries(D))Z.set(ce,be);return new Ie(Z).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>A,deviceToExecutionProviders:()=>f,isONNXProxy:()=>$,isONNXTensor:()=>b});var i=t("./src/env.js"),n=t("?2ce3"),o=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),d=[];let p,u;const h=Symbol.for("onnxruntime");if(h in globalThis)u=globalThis[h];else if(i.apis.IS_NODE_ENV){switch(u=n??(s||(s=t.t(n,2))),process.platform){case"win32":d.push("dml");break;case"linux":process.arch==="x64"&&d.push("cuda");break}d.push("cpu"),p=["cpu"]}else u=o,i.apis.IS_WEBNN_AVAILABLE&&d.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),i.apis.IS_WEBGPU_AVAILABLE&&d.push("webgpu"),d.push("wasm"),p=["wasm"];const w=u.InferenceSession;function f(T=null){if(!T)return p;switch(T){case"auto":return d;case"gpu":return d.filter(g=>["webgpu","cuda","dml","webnn-gpu"].includes(g))}if(d.includes(T))return[l[T]??T];throw new Error(`Unsupported device: "${T}". Should be one of: ${d.join(", ")}.`)}let P=null;async function A(T,g,M){P&&await P;const E=w.create(T,g);P??(P=E);const k=await E;return k.config=M,k}function b(T){return T instanceof u.Tensor}const y=u==null?void 0:u.env;y!=null&&y.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!y.wasm.wasmPaths&&(y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${i.env.version}/dist/`),y.wasm.proxy=!1),y!=null&&y.webgpu&&(y.webgpu.powerPreference="high-performance");function $(){var T;return(T=y==null?void 0:y.wasm)==null?void 0:T.proxy}i.env.backends.onnx=y},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>o,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(d){super(),this.config=d}static async from_pretrained(d,p){const u=await(0,n.getModelJSON)(d,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(u)}}function a(l,d){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${d} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>T,center_to_corners_format:()=>u,post_process_instance_segmentation:()=>$,post_process_object_detection:()=>h,post_process_panoptic_segmentation:()=>y,post_process_semantic_segmentation:()=>w});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var o=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function d(g,M,E=0,k=null){const B=g/M;let N=(0,n.bankers_round)(B)*M;return k!==null&&N>k&&(N=Math.floor(B)*M),NM&&O.push(ne)}else{let ne=(0,n.max)(R.data)[1];if(ne===V-1||(G=(0,n.softmax)(R.data),G[ne]ye*Q[(_e+1)%2])),ie.boxes.push(X),ie.classes.push(ne),ie.scores.push(G[ne])}}Y.push(ie)}return Y}function w(g,M=null){const E=g.logits,k=E.dims[0];if(M!==null&&M.length!==k)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const B=[];for(let N=0;NQ[O]&&(Q[O]=R[O],ie[O]=we)}const le=new Array(q.dims[0]);for(let we=0;wewe!==void 0);B.push({segmentation:H,labels:ae})}return B}function f(g,M,E,k){const B=[],N=[],J=[];for(let q=0;qE&&(B.push(Y),N.push(ie),J.push(H))}return[B,N,J]}function P(g,M,E,k=.5,B=.8){const N=[];let J=0,q=0;const V=M[E].data;for(let H=0;H=k&&++q;let Y=J>0&&q>0;return Y&&(Y=J/q>B),[Y,N]}function A(g,M,E,k,B,N=null,J=null){const[q,V]=J??g[0].dims,Y=new i.Tensor("int32",new Int32Array(q*V),[q,V]),H=[];if(J!==null)for(let we=0;weie[G]&&(Q[G]=we,ie[G]=O[G])}let le=0;const ae=Y.data;for(let we=0;we200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(g,M)/Math.min(g,M)}`);let N=Math.round(g/E)*E,J=Math.round(M/E)*E;if(N*J>B){const q=Math.sqrt(g*M/B);N=Math.floor(g/q/E)*E,J=Math.floor(M/q/E)*E}else if(N*JN?Y=Math.floor(N*V/B):N>B&&(V=Math.floor(B*Y/N)),await M.resize(Y,V,{resample:k}))}async crop_margin(M,E=200){const k=M.clone().grayscale(),B=(0,n.min)(k.data)[0],J=(0,n.max)(k.data)[0]-B;if(J===0)return M;const q=E/255;let V=k.width,Y=k.height,H=0,Q=0;const ie=k.data;for(let le=0;lethis.preprocess(N)));return{pixel_values:(0,i.stack)(k.map(N=>N.pixel_values),0),original_sizes:k.map(N=>N.original_size),reshaped_input_sizes:k.map(N=>N.reshaped_input_size)}}static async from_pretrained(M,E){const k=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,E);return new this(k)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(l,d){super(),this.config=l,this.components=d}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,d={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...d})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...d){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...d);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,d){const[p,u]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,d):{},Promise.all(this.classes.filter(h=>h in this).map(async h=>{const w=await this[h].from_pretrained(l,d);return[h.replace(/_class$/,""),w]})).then(Object.fromEntries)]);return new this(p,u)}}re(o,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),re(o,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>d,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js");async function n(p,u){return await(0,i.getModelJSON)(p,"config.json",!0,u)}function o(p){const u={};let h={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":h=o(p.text_config);break;case"moondream1":h=o(p.phi_config);break;case"musicgen":h=o(p.decoder);break;case"multi_modality":h=o(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const f=o(p.decoder),P="num_decoder_layers"in f,A=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return P?(A.num_decoder_layers=f.num_decoder_layers,A.num_decoder_heads=f.num_decoder_heads,A.decoder_hidden_size=f.decoder_hidden_size,A.num_encoder_layers=f.num_encoder_layers,A.num_encoder_heads=f.num_encoder_heads,A.encoder_hidden_size=f.encoder_hidden_size):(A.num_layers=f.num_layers,A.num_heads=f.num_heads,A.hidden_size=f.hidden_size),A}const w={...h,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const f in u)w[f]=p[u[f]];return w}function a(p,{prefix:u="past_key_values",batch_size:h=1}={}){const w={},f=p.normalized_config;if(f.is_encoder_decoder&&"num_encoder_heads"in f&&"num_decoder_heads"in f){const P=f.encoder_dim_kv??f.encoder_hidden_size/f.num_encoder_heads,A=f.decoder_dim_kv??f.decoder_hidden_size/f.num_decoder_heads,b=[h,f.num_encoder_heads,0,P],y=[h,f.num_decoder_heads,0,A];for(let $=0;${var k,B;t.r(r),t.d(r,{apis:()=>A,env:()=>M});var s=t("?569f"),i=t("?3f59"),n=t("?154a");const o="3.4.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((k=self.constructor)==null?void 0:k.name)==="DedicatedWorkerGlobalScope",d=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,u=typeof navigator<"u"&&"ml"in navigator,h=typeof process<"u",w=h&&((B=process==null?void 0:process.release)==null?void 0:B.name)==="node",f=!E(s),P=!E(i),A=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:d,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:u,IS_PROCESS_AVAILABLE:h,IS_NODE_ENV:w,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:P}),b=f&&P;let y="./";if(b){const N=Object({url:self.location.href}).url;N?y=i.dirname(i.dirname(n.fileURLToPath(N))):typeof __dirname<"u"&&(y=i.dirname(__dirname))}const $=b?i.join(y,"/.cache/"):null,T="/models/",g=b?i.join(y,T):T,M={version:o,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:g,useFS:f,useBrowserCache:d,useFSCache:f,cacheDir:$,useCustomCache:!1,customCache:null};function E(N){return Object.keys(N).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>i});var s=t("./src/utils/core.js");class i{constructor(o){re(this,"max_length",20);re(this,"max_new_tokens",null);re(this,"min_length",0);re(this,"min_new_tokens",null);re(this,"early_stopping",!1);re(this,"max_time",null);re(this,"do_sample",!1);re(this,"num_beams",1);re(this,"num_beam_groups",1);re(this,"penalty_alpha",null);re(this,"use_cache",!0);re(this,"temperature",1);re(this,"top_k",50);re(this,"top_p",1);re(this,"typical_p",1);re(this,"epsilon_cutoff",0);re(this,"eta_cutoff",0);re(this,"diversity_penalty",0);re(this,"repetition_penalty",1);re(this,"encoder_repetition_penalty",1);re(this,"length_penalty",1);re(this,"no_repeat_ngram_size",0);re(this,"bad_words_ids",null);re(this,"force_words_ids",null);re(this,"renormalize_logits",!1);re(this,"constraints",null);re(this,"forced_bos_token_id",null);re(this,"forced_eos_token_id",null);re(this,"remove_invalid_values",!1);re(this,"exponential_decay_length_penalty",null);re(this,"suppress_tokens",null);re(this,"streamer",null);re(this,"begin_suppress_tokens",null);re(this,"forced_decoder_ids",null);re(this,"guidance_scale",null);re(this,"num_return_sequences",1);re(this,"output_attentions",!1);re(this,"output_hidden_states",!1);re(this,"output_scores",!1);re(this,"return_dict_in_generate",!1);re(this,"pad_token_id",null);re(this,"bos_token_id",null);re(this,"eos_token_id",null);re(this,"encoder_no_repeat_ngram_size",0);re(this,"decoder_start_token_id",null);re(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(o,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>b,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>d,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>o,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>P,NoBadWordsLogitsProcessor:()=>A,NoRepeatNGramLogitsProcessor:()=>h,RepetitionPenaltyLogitsProcessor:()=>w,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>y,TopKLogitsWarper:()=>T,TopPLogitsWarper:()=>$,WhisperTimeStampLogitsProcessor:()=>u});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var i=t("./src/utils/maths.js");class n extends s.Callable{_call(M,E){throw Error("`_call` should be implemented in a subclass")}}class o extends s.Callable{_call(M,E){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(M){this.processors.push(M)}extend(M){this.processors.push(...M)}_call(M,E){let k=E;for(const B of this.processors)k=B(M,k);return k}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,E){for(let k=0;k=1&&N[N.length-1]>=this.timestamp_begin,q=N.length<2||N[N.length-2]>=this.timestamp_begin;if(J&&(q?B.subarray(this.timestamp_begin).fill(-1/0):B.subarray(0,this.eos_token_id).fill(-1/0)),M[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Q=this.timestamp_begin+this.max_initial_timestamp_index;B.subarray(Q+1).fill(-1/0)}const V=(0,i.log_softmax)(B),Y=Math.log(V.subarray(this.timestamp_begin).map(Math.exp).reduce((Q,ie)=>Q+ie)),H=(0,i.max)(V.subarray(0,this.timestamp_begin))[0];Y>H&&B.subarray(0,this.timestamp_begin).fill(-1/0)}return E}}class h extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const E=M.length,k=[];for(let N=0;N1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,E){if(E.dims[0]!==2*M.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${E.dims[0]} for the logits and ${M.length} for the input ids.`);const k=M.length,B=E.slice([0,k],null),N=E.slice([k,E.dims[0]],null);for(let J=0;J1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=M,this.filter_value=E,this.min_tokens_to_keep=k}}class T extends o{constructor(M,{filter_value:E=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(M)||M<0)throw new Error(`\`top_k\` must be a positive integer, but is ${M}`);this.top_k=Math.max(M,k),this.filter_value=E}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>o});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class o extends s.Callable{constructor(u){super(),this.generation_config=u}async _call(u){return this.sample(u)}async sample(u){throw Error("sample should be implemented in subclasses.")}getLogits(u,h){let w=u.dims.at(-1),f=u.data;if(h===-1)f=f.slice(-w);else{let P=h*w;f=f.slice(P,P+w)}return f}randomSelect(u){let h=0;for(let f=0;f1)return new d(u);if(u.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${u.num_return_sequences}.`);return new a(u)}}class a extends o{async sample(u){const h=(0,n.max)(u.data)[1];return[[BigInt(h),0]]}}class l extends o{async sample(u){let h=u.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[w,f]=await(0,i.topk)(u,h),P=(0,n.softmax)(w.data);return Array.from({length:this.generation_config.num_beams},()=>{const A=this.randomSelect(P);return[f.data[A],Math.log(P[A])]})}}class d extends o{async sample(u){let h=u.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[w,f]=await(0,i.topk)(u,h),P=(0,n.softmax)(w.data);return Array.from({length:this.generation_config.num_beams},(A,b)=>[f.data[b],Math.log(P[b])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>o,StoppingCriteria:()=>i,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class i extends s.Callable{_call(p,u){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof i&&(p=[p]),this.criteria.push(...p)}_call(p,u){const h=new Array(p.length).fill(!1);for(const w of this.criteria){const f=w(p,u);for(let P=0;Pu.length>=this.max_length)}}class a extends i{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,u){return p.map(h=>{const w=h.at(-1);return this.eos_token_id.some(f=>w==f)})}}class l extends i{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,u){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>o,TextStreamer:()=>l,WhisperTextStreamer:()=>d});var s=t("./src/utils/core.js"),i=t("./src/tokenizers.js"),n=t("./src/env.js");class o{put(u){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends o{constructor(u,{skip_prompt:h=!1,callback_function:w=null,token_callback_function:f=null,skip_special_tokens:P=!0,decode_kwargs:A={},...b}={}){super(),this.tokenizer=u,this.skip_prompt=h,this.callback_function=w??a,this.token_callback_function=f,this.decode_kwargs={skip_special_tokens:P,...A,...b},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(u){var A;if(u.length>1)throw Error("TextStreamer only supports batch size of 1");const h=this.next_tokens_are_prompt;if(h&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const w=u[0];(A=this.token_callback_function)==null||A.call(this,w),this.token_cache=(0,s.mergeArrays)(this.token_cache,w);const f=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let P;h||f.endsWith(` +`)?(P=f.slice(this.print_len),this.token_cache=[],this.print_len=0):f.length>0&&(0,i.is_chinese_char)(f.charCodeAt(f.length-1))?(P=f.slice(this.print_len),this.print_len+=P.length):(P=f.slice(this.print_len,f.lastIndexOf(" ")+1),this.print_len+=P.length),this.on_finalized_text(P,!1)}end(){let u;this.token_cache.length>0?(u=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):u="",this.next_tokens_are_prompt=!0,this.on_finalized_text(u,!0)}on_finalized_text(u,h){var w,f;u.length>0&&((w=this.callback_function)==null||w.call(this,u)),h&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((f=this.callback_function)==null||f.call(this,` +`))}}class d extends l{constructor(u,{skip_prompt:h=!1,callback_function:w=null,token_callback_function:f=null,on_chunk_start:P=null,on_chunk_end:A=null,on_finalize:b=null,time_precision:y=.02,skip_special_tokens:$=!0,decode_kwargs:T={}}={}){super(u,{skip_prompt:h,skip_special_tokens:$,callback_function:w,token_callback_function:f,decode_kwargs:T}),this.timestamp_begin=u.timestamp_begin,this.on_chunk_start=P,this.on_chunk_end=A,this.on_finalize=b,this.time_precision=y,this.waiting_for_timestamp=!1}put(u){var w,f;if(u.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const h=u[0];if(h.length===1){const P=Number(h[0])-this.timestamp_begin;if(P>=0){const A=P*this.time_precision;this.waiting_for_timestamp?(w=this.on_chunk_end)==null||w.call(this,A):(f=this.on_chunk_start)==null||f.call(this,A),this.waiting_for_timestamp=!this.waiting_for_timestamp,u=[[]]}}return super.put(u)}end(){var u;super.end(),(u=this.on_finalize)==null||u.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ua,ASTModel:()=>ja,ASTPreTrainedModel:()=>Gi,AlbertForMaskedLM:()=>j,AlbertForQuestionAnswering:()=>F,AlbertForSequenceClassification:()=>ue,AlbertModel:()=>Cn,AlbertPreTrainedModel:()=>Ss,AutoModel:()=>Tu,AutoModelForAudioClassification:()=>tb,AutoModelForAudioFrameClassification:()=>sb,AutoModelForAudioTextToText:()=>pb,AutoModelForCTC:()=>eb,AutoModelForCausalLM:()=>V0,AutoModelForDepthEstimation:()=>ab,AutoModelForDocumentQuestionAnswering:()=>nb,AutoModelForImageClassification:()=>H0,AutoModelForImageFeatureExtraction:()=>cb,AutoModelForImageMatting:()=>ib,AutoModelForImageSegmentation:()=>q0,AutoModelForImageTextToText:()=>ub,AutoModelForImageToImage:()=>ob,AutoModelForMaskGeneration:()=>Z0,AutoModelForMaskedLM:()=>W0,AutoModelForNormalEstimation:()=>lb,AutoModelForObjectDetection:()=>J0,AutoModelForPoseEstimation:()=>db,AutoModelForQuestionAnswering:()=>G0,AutoModelForSemanticSegmentation:()=>Q0,AutoModelForSeq2SeqLM:()=>R0,AutoModelForSequenceClassification:()=>z0,AutoModelForSpeechSeq2Seq:()=>N0,AutoModelForTextToSpectrogram:()=>j0,AutoModelForTextToWaveform:()=>U0,AutoModelForTokenClassification:()=>B0,AutoModelForUniversalSegmentation:()=>X0,AutoModelForVision2Seq:()=>K0,AutoModelForXVector:()=>rb,AutoModelForZeroShotObjectDetection:()=>Y0,BartForConditionalGeneration:()=>Wt,BartForSequenceClassification:()=>Ot,BartModel:()=>kt,BartPretrainedModel:()=>Ct,BaseModelOutput:()=>Pe,BeitForImageClassification:()=>kl,BeitModel:()=>$l,BeitPreTrainedModel:()=>na,BertForMaskedLM:()=>Ie,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Le,BertForTokenClassification:()=>Ne,BertModel:()=>Ae,BertPreTrainedModel:()=>Te,BlenderbotForConditionalGeneration:()=>Zt,BlenderbotModel:()=>Gt,BlenderbotPreTrainedModel:()=>gs,BlenderbotSmallForConditionalGeneration:()=>ws,BlenderbotSmallModel:()=>Zr,BlenderbotSmallPreTrainedModel:()=>gr,BloomForCausalLM:()=>No,BloomModel:()=>Ro,BloomPreTrainedModel:()=>wi,CLIPModel:()=>Zi,CLIPPreTrainedModel:()=>js,CLIPSegForImageSegmentation:()=>eo,CLIPSegModel:()=>nn,CLIPSegPreTrainedModel:()=>sn,CLIPTextModel:()=>Yc,CLIPTextModelWithProjection:()=>Ja,CLIPVisionModel:()=>Zc,CLIPVisionModelWithProjection:()=>Qn,CamembertForMaskedLM:()=>xs,CamembertForQuestionAnswering:()=>Ds,CamembertForSequenceClassification:()=>Ts,CamembertForTokenClassification:()=>Es,CamembertModel:()=>us,CamembertPreTrainedModel:()=>Ur,CausalLMOutput:()=>Fn,CausalLMOutputWithPast:()=>Cx,ChineseCLIPModel:()=>rl,ChineseCLIPPreTrainedModel:()=>tl,ClapAudioModelWithProjection:()=>yM,ClapModel:()=>gM,ClapPreTrainedModel:()=>Wl,ClapTextModelWithProjection:()=>wM,CodeGenForCausalLM:()=>Vr,CodeGenModel:()=>In,CodeGenPreTrainedModel:()=>ti,CohereForCausalLM:()=>vo,CohereModel:()=>bo,CoherePreTrainedModel:()=>ci,ConvBertForMaskedLM:()=>jt,ConvBertForQuestionAnswering:()=>Fs,ConvBertForSequenceClassification:()=>dr,ConvBertForTokenClassification:()=>ds,ConvBertModel:()=>nr,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>hy,ConvNextModel:()=>py,ConvNextPreTrainedModel:()=>ru,ConvNextV2ForImageClassification:()=>_y,ConvNextV2Model:()=>my,ConvNextV2PreTrainedModel:()=>su,DPTForDepthEstimation:()=>qw,DPTModel:()=>an,DPTPreTrainedModel:()=>Pr,DacDecoderModel:()=>a0,DacDecoderOutput:()=>n0,DacEncoderModel:()=>o0,DacEncoderOutput:()=>s0,DacModel:()=>i0,DacPreTrainedModel:()=>Jl,DebertaForMaskedLM:()=>et,DebertaForQuestionAnswering:()=>zt,DebertaForSequenceClassification:()=>it,DebertaForTokenClassification:()=>rr,DebertaModel:()=>Be,DebertaPreTrainedModel:()=>mr,DebertaV2ForMaskedLM:()=>hs,DebertaV2ForQuestionAnswering:()=>_s,DebertaV2ForSequenceClassification:()=>Er,DebertaV2ForTokenClassification:()=>ms,DebertaV2Model:()=>ps,DebertaV2PreTrainedModel:()=>Ir,DecisionTransformerModel:()=>NM,DecisionTransformerPreTrainedModel:()=>RM,DeiTForImageClassification:()=>c,DeiTModel:()=>ca,DeiTPreTrainedModel:()=>da,DepthAnythingForDepthEstimation:()=>Xw,DepthAnythingPreTrainedModel:()=>Qw,DepthProForDepthEstimation:()=>ty,DepthProPreTrainedModel:()=>ey,DetrForObjectDetection:()=>Al,DetrForSegmentation:()=>ia,DetrModel:()=>Il,DetrObjectDetectionOutput:()=>oa,DetrPreTrainedModel:()=>xi,DetrSegmentationOutput:()=>Fl,Dinov2ForImageClassification:()=>gy,Dinov2Model:()=>fy,Dinov2PreTrainedModel:()=>nu,Dinov2WithRegistersForImageClassification:()=>yy,Dinov2WithRegistersModel:()=>wy,Dinov2WithRegistersPreTrainedModel:()=>iu,DistilBertForMaskedLM:()=>Js,DistilBertForQuestionAnswering:()=>Xs,DistilBertForSequenceClassification:()=>qs,DistilBertForTokenClassification:()=>Qs,DistilBertModel:()=>Ps,DistilBertPreTrainedModel:()=>Qr,DonutSwinModel:()=>uy,DonutSwinPreTrainedModel:()=>cy,EfficientNetForImageClassification:()=>PM,EfficientNetModel:()=>EM,EfficientNetPreTrainedModel:()=>_u,ElectraForMaskedLM:()=>Os,ElectraForQuestionAnswering:()=>qr,ElectraForSequenceClassification:()=>jr,ElectraForTokenClassification:()=>dt,ElectraModel:()=>cs,ElectraPreTrainedModel:()=>Dr,EsmForMaskedLM:()=>Zs,EsmForSequenceClassification:()=>en,EsmForTokenClassification:()=>Lr,EsmModel:()=>Ys,EsmPreTrainedModel:()=>fs,ExaoneForCausalLM:()=>mt,ExaoneModel:()=>mo,ExaonePreTrainedModel:()=>Us,FalconForCausalLM:()=>fM,FalconModel:()=>_M,FalconPreTrainedModel:()=>pu,FastViTForImageClassification:()=>wl,FastViTModel:()=>gl,FastViTPreTrainedModel:()=>Zo,Florence2ForConditionalGeneration:()=>Qi,Florence2PreTrainedModel:()=>Qa,GLPNForDepthEstimation:()=>dy,GLPNModel:()=>ly,GLPNPreTrainedModel:()=>tu,GPT2LMHeadModel:()=>Yn,GPT2Model:()=>ol,GPT2PreTrainedModel:()=>to,GPTBigCodeForCausalLM:()=>co,GPTBigCodeModel:()=>ll,GPTBigCodePreTrainedModel:()=>Oe,GPTJForCausalLM:()=>kn,GPTJModel:()=>lo,GPTJPreTrainedModel:()=>ao,GPTNeoForCausalLM:()=>io,GPTNeoModel:()=>no,GPTNeoPreTrainedModel:()=>Zn,GPTNeoXForCausalLM:()=>oo,GPTNeoXModel:()=>al,GPTNeoXPreTrainedModel:()=>ei,Gemma2ForCausalLM:()=>Po,Gemma2Model:()=>Eo,Gemma2PreTrainedModel:()=>pi,Gemma3ForCausalLM:()=>So,Gemma3Model:()=>Co,Gemma3PreTrainedModel:()=>hi,GemmaForCausalLM:()=>To,GemmaModel:()=>xo,GemmaPreTrainedModel:()=>ui,GlmForCausalLM:()=>ft,GlmModel:()=>ho,GlmPreTrainedModel:()=>ii,GraniteForCausalLM:()=>Mo,GraniteModel:()=>yo,GranitePreTrainedModel:()=>di,GroundingDinoForObjectDetection:()=>by,GroundingDinoPreTrainedModel:()=>My,GroupViTModel:()=>fl,GroupViTPreTrainedModel:()=>_l,HeliumForCausalLM:()=>ni,HeliumModel:()=>po,HeliumPreTrainedModel:()=>si,HieraForImageClassification:()=>C,HieraModel:()=>v,HieraPreTrainedModel:()=>m,HubertForCTC:()=>Jy,HubertForSequenceClassification:()=>Yy,HubertModel:()=>Xy,HubertPreTrainedModel:()=>hx,IJepaForImageClassification:()=>qo,IJepaModel:()=>Ho,IJepaPreTrainedModel:()=>vi,Idefics3ForConditionalGeneration:()=>Hn,Idefics3PreTrainedModel:()=>Xa,ImageMattingOutput:()=>mb,JAISLMHeadModel:()=>so,JAISModel:()=>ro,JAISPreTrainedModel:()=>$n,JinaCLIPModel:()=>sl,JinaCLIPPreTrainedModel:()=>Jn,JinaCLIPTextModel:()=>nl,JinaCLIPVisionModel:()=>il,LiteWhisperForConditionalGeneration:()=>Wa,LlamaForCausalLM:()=>uo,LlamaModel:()=>ri,LlamaPreTrainedModel:()=>on,LlavaForConditionalGeneration:()=>Kn,LlavaOnevisionForConditionalGeneration:()=>Ha,LlavaPreTrainedModel:()=>Ka,LongT5ForConditionalGeneration:()=>qe,LongT5Model:()=>We,LongT5PreTrainedModel:()=>Ce,M2M100ForConditionalGeneration:()=>Iy,M2M100Model:()=>ky,M2M100PreTrainedModel:()=>lu,MBartForCausalLM:()=>xr,MBartForConditionalGeneration:()=>fr,MBartForSequenceClassification:()=>Yr,MBartModel:()=>vr,MBartPreTrainedModel:()=>Ut,MPNetForMaskedLM:()=>zr,MPNetForQuestionAnswering:()=>Fr,MPNetForSequenceClassification:()=>En,MPNetForTokenClassification:()=>Bs,MPNetModel:()=>Tn,MPNetPreTrainedModel:()=>Xr,MT5ForConditionalGeneration:()=>ht,MT5Model:()=>Ze,MT5PreTrainedModel:()=>Ke,MarianMTModel:()=>$y,MarianModel:()=>Sy,MarianPreTrainedModel:()=>au,MaskFormerForInstanceSegmentation:()=>ay,MaskFormerModel:()=>oy,MaskFormerPreTrainedModel:()=>eu,MaskedLMOutput:()=>wr,Metric3DForDepthEstimation:()=>sy,Metric3DPreTrainedModel:()=>ry,Metric3Dv2ForDepthEstimation:()=>iy,Metric3Dv2PreTrainedModel:()=>ny,MgpstrForSceneTextRecognition:()=>GM,MgpstrModelOutput:()=>VM,MgpstrPreTrainedModel:()=>WM,MimiDecoderModel:()=>r0,MimiDecoderOutput:()=>ZM,MimiEncoderModel:()=>t0,MimiEncoderOutput:()=>YM,MimiModel:()=>e0,MimiPreTrainedModel:()=>Xl,MistralForCausalLM:()=>pM,MistralModel:()=>uM,MistralPreTrainedModel:()=>cu,MobileBertForMaskedLM:()=>Ls,MobileBertForQuestionAnswering:()=>Ar,MobileBertForSequenceClassification:()=>zs,MobileBertModel:()=>br,MobileBertPreTrainedModel:()=>Cs,MobileLLMForCausalLM:()=>_o,MobileLLMModel:()=>_t,MobileLLMPreTrainedModel:()=>An,MobileNetV1ForImageClassification:()=>SM,MobileNetV1ForSemanticSegmentation:()=>$M,MobileNetV1Model:()=>CM,MobileNetV1PreTrainedModel:()=>Kl,MobileNetV2ForImageClassification:()=>IM,MobileNetV2ForSemanticSegmentation:()=>AM,MobileNetV2Model:()=>kM,MobileNetV2PreTrainedModel:()=>Hl,MobileNetV3ForImageClassification:()=>OM,MobileNetV3ForSemanticSegmentation:()=>DM,MobileNetV3Model:()=>FM,MobileNetV3PreTrainedModel:()=>ql,MobileNetV4ForImageClassification:()=>zM,MobileNetV4ForSemanticSegmentation:()=>BM,MobileNetV4Model:()=>LM,MobileNetV4PreTrainedModel:()=>Ql,MobileViTForImageClassification:()=>vl,MobileViTModel:()=>bl,MobileViTPreTrainedModel:()=>ea,MobileViTV2ForImageClassification:()=>Tl,MobileViTV2Model:()=>xl,MobileViTV2PreTrainedModel:()=>ta,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>ee,ModernBertForTokenClassification:()=>ce,ModernBertModel:()=>Z,ModernBertPreTrainedModel:()=>D,Moondream1ForConditionalGeneration:()=>qa,MoonshineForConditionalGeneration:()=>Ga,MoonshineModel:()=>Jc,MoonshinePreTrainedModel:()=>Hi,MptForCausalLM:()=>Uo,MptModel:()=>jo,MptPreTrainedModel:()=>yi,MultiModalityCausalLM:()=>UM,MultiModalityPreTrainedModel:()=>jM,MusicgenForCausalLM:()=>gx,MusicgenForConditionalGeneration:()=>gu,MusicgenModel:()=>fx,MusicgenPreTrainedModel:()=>fu,NomicBertModel:()=>ve,NomicBertPreTrainedModel:()=>be,OPTForCausalLM:()=>Wo,OPTModel:()=>Vo,OPTPreTrainedModel:()=>Mi,Olmo2ForCausalLM:()=>li,Olmo2Model:()=>wo,Olmo2PreTrainedModel:()=>ai,OlmoForCausalLM:()=>go,OlmoModel:()=>fo,OlmoPreTrainedModel:()=>oi,OpenELMForCausalLM:()=>ko,OpenELMModel:()=>$o,OpenELMPreTrainedModel:()=>mi,OwlViTForObjectDetection:()=>Pl,OwlViTModel:()=>El,OwlViTPreTrainedModel:()=>ra,Owlv2ForObjectDetection:()=>Sl,Owlv2Model:()=>Cl,Owlv2PreTrainedModel:()=>sa,PaliGemmaForConditionalGeneration:()=>Ji,PaliGemmaPreTrainedModel:()=>Xi,PatchTSMixerForPrediction:()=>QM,PatchTSMixerModel:()=>qM,PatchTSMixerPreTrainedModel:()=>yu,PatchTSTForPrediction:()=>HM,PatchTSTModel:()=>KM,PatchTSTPreTrainedModel:()=>wu,Phi3ForCausalLM:()=>Bo,Phi3Model:()=>zo,Phi3PreTrainedModel:()=>gi,Phi3VForCausalLM:()=>Ns,Phi3VPreTrainedModel:()=>Yi,PhiForCausalLM:()=>Lo,PhiModel:()=>Do,PhiPreTrainedModel:()=>fi,PreTrainedModel:()=>U,PretrainedMixin:()=>It,PvtForImageClassification:()=>cl,PvtModel:()=>dl,PvtPreTrainedModel:()=>Jo,PyAnnoteForAudioFrameClassification:()=>zy,PyAnnoteModel:()=>Ly,PyAnnotePreTrainedModel:()=>du,QuestionAnsweringModelOutput:()=>Cr,Qwen2ForCausalLM:()=>Ao,Qwen2Model:()=>Io,Qwen2PreTrainedModel:()=>_i,Qwen2VLForConditionalGeneration:()=>Oo,Qwen2VLPreTrainedModel:()=>Fo,RTDetrForObjectDetection:()=>Dl,RTDetrModel:()=>Ol,RTDetrObjectDetectionOutput:()=>Ll,RTDetrPreTrainedModel:()=>aa,ResNetForImageClassification:()=>se,ResNetModel:()=>W,ResNetPreTrainedModel:()=>I,RoFormerForMaskedLM:()=>je,RoFormerForQuestionAnswering:()=>ut,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>Xe,RoFormerModel:()=>Fe,RoFormerPreTrainedModel:()=>Re,RobertaForMaskedLM:()=>Rt,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Jt,RobertaForTokenClassification:()=>qt,RobertaModel:()=>ur,RobertaPreTrainedModel:()=>Ht,SamImageSegmentationOutput:()=>Cy,SamModel:()=>Py,SamPreTrainedModel:()=>Ey,SapiensForDepthEstimation:()=>Yw,SapiensForNormalEstimation:()=>Zw,SapiensForSemanticSegmentation:()=>Jw,SapiensPreTrainedModel:()=>Nl,SegformerForImageClassification:()=>bM,SegformerForSemanticSegmentation:()=>vM,SegformerModel:()=>_x,SegformerPreTrainedModel:()=>Gl,Seq2SeqLMOutput:()=>Px,SequenceClassifierOutput:()=>bt,SiglipModel:()=>Ya,SiglipPreTrainedModel:()=>Xn,SiglipTextModel:()=>Za,SiglipVisionModel:()=>el,SmolVLMForConditionalGeneration:()=>qn,SnacDecoderModel:()=>c0,SnacEncoderModel:()=>d0,SnacModel:()=>l0,SnacPreTrainedModel:()=>Yl,SpeechT5ForSpeechToText:()=>oM,SpeechT5ForTextToSpeech:()=>aM,SpeechT5HifiGan:()=>lM,SpeechT5Model:()=>mx,SpeechT5PreTrainedModel:()=>Vl,SqueezeBertForMaskedLM:()=>_r,SqueezeBertForQuestionAnswering:()=>Pn,SqueezeBertForSequenceClassification:()=>Rs,SqueezeBertModel:()=>cr,SqueezeBertPreTrainedModel:()=>Jr,StableLmForCausalLM:()=>TM,StableLmModel:()=>xM,StableLmPreTrainedModel:()=>mu,Starcoder2ForCausalLM:()=>mM,Starcoder2Model:()=>hM,Starcoder2PreTrainedModel:()=>uu,StyleTextToSpeech2Model:()=>iM,StyleTextToSpeech2PreTrainedModel:()=>nM,Swin2SRForImageSuperResolution:()=>Bt,Swin2SRModel:()=>gt,Swin2SRPreTrainedModel:()=>ot,SwinForImageClassification:()=>ze,SwinForSemanticSegmentation:()=>Ye,SwinModel:()=>Ee,SwinPreTrainedModel:()=>ge,T5ForConditionalGeneration:()=>he,T5Model:()=>de,T5PreTrainedModel:()=>te,TableTransformerForObjectDetection:()=>Bl,TableTransformerModel:()=>zl,TableTransformerObjectDetectionOutput:()=>Rl,TableTransformerPreTrainedModel:()=>la,TokenClassifierOutput:()=>pr,TrOCRForCausalLM:()=>cM,TrOCRPreTrainedModel:()=>dM,UltravoxModel:()=>JM,UltravoxPreTrainedModel:()=>XM,UniSpeechForCTC:()=>jy,UniSpeechForSequenceClassification:()=>Uy,UniSpeechModel:()=>Ny,UniSpeechPreTrainedModel:()=>jl,UniSpeechSatForAudioFrameClassification:()=>Ky,UniSpeechSatForCTC:()=>Wy,UniSpeechSatForSequenceClassification:()=>Gy,UniSpeechSatModel:()=>Vy,UniSpeechSatPreTrainedModel:()=>ua,ViTForImageClassification:()=>Ko,ViTMAEModel:()=>pl,ViTMAEPreTrainedModel:()=>ul,ViTMSNForImageClassification:()=>ml,ViTMSNModel:()=>hl,ViTMSNPreTrainedModel:()=>Yo,ViTModel:()=>Go,ViTPreTrainedModel:()=>bi,VisionEncoderDecoderModel:()=>qi,VitMatteForImageMatting:()=>Ml,VitMattePreTrainedModel:()=>yl,VitPoseForPoseEstimation:()=>Xo,VitPosePreTrainedModel:()=>Qo,VitsModel:()=>hu,VitsModelOutput:()=>_b,VitsPreTrainedModel:()=>MM,Wav2Vec2BertForCTC:()=>qy,Wav2Vec2BertForSequenceClassification:()=>Qy,Wav2Vec2BertModel:()=>Hy,Wav2Vec2BertPreTrainedModel:()=>Ul,Wav2Vec2ForAudioFrameClassification:()=>Dy,Wav2Vec2ForCTC:()=>Fy,Wav2Vec2ForSequenceClassification:()=>Oy,Wav2Vec2Model:()=>Ay,Wav2Vec2PreTrainedModel:()=>ln,WavLMForAudioFrameClassification:()=>sM,WavLMForCTC:()=>eM,WavLMForSequenceClassification:()=>tM,WavLMForXVector:()=>rM,WavLMModel:()=>Zy,WavLMPreTrainedModel:()=>Ti,WeSpeakerResNetModel:()=>Ry,WeSpeakerResNetPreTrainedModel:()=>By,WhisperForConditionalGeneration:()=>Ki,WhisperModel:()=>Va,WhisperPreTrainedModel:()=>Gn,XLMForQuestionAnswering:()=>za,XLMForSequenceClassification:()=>La,XLMForTokenClassification:()=>Vi,XLMModel:()=>tn,XLMPreTrainedModel:()=>ir,XLMRobertaForMaskedLM:()=>Ra,XLMRobertaForQuestionAnswering:()=>Wi,XLMRobertaForSequenceClassification:()=>Sn,XLMRobertaForTokenClassification:()=>Na,XLMRobertaModel:()=>Ba,XLMRobertaPreTrainedModel:()=>ys,XLMWithLMHeadModel:()=>rn,XVectorOutput:()=>hb,YolosForObjectDetection:()=>xy,YolosModel:()=>vy,YolosObjectDetectionOutput:()=>Ty,YolosPreTrainedModel:()=>ou});var s=t("./src/configs.js"),i=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),o=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),d=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),u=t("./src/generation/configuration_utils.js"),h=t("./src/utils/tensor.js"),w=t("./src/utils/image.js"),f=t("./src/utils/maths.js"),P=t("./src/generation/stopping_criteria.js"),A=t("./src/generation/logits_sampler.js"),b=t("./src/env.js"),y=t("./src/models/whisper/generation_whisper.js"),$=t("./src/models/whisper/common_whisper.js");const T={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},g=new Map,M=new Map,E=new Map;async function k(x,S,L){var yr;const oe=((yr=L.config)==null?void 0:yr["transformers.js_config"])??{};let fe=L.device??oe.device;fe&&typeof fe!="string"&&(fe.hasOwnProperty(S)?fe=fe[S]:(console.warn(`device not specified for "${S}". Using the default device.`),fe=null));const me=fe??(b.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,i.deviceToExecutionProviders)(me);let De=L.dtype??oe.dtype;if(typeof De!="string"&&(De&&De.hasOwnProperty(S)?De=De[S]:(De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${S}". Using the default dtype (${De}) for this device (${me}).`))),De===n.DATA_TYPES.auto){let Pt=oe.dtype;typeof Pt!="string"&&(Pt=Pt[S]),Pt&&Pt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Pt)?De=Pt:De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32}const Ge=De;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ge)){if(Ge===n.DATA_TYPES.fp16&&me==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${me}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ge}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const Je=oe.kv_cache_dtype?typeof oe.kv_cache_dtype=="string"?oe.kv_cache_dtype:oe.kv_cache_dtype[Ge]??"float32":void 0;if(Je&&!["float32","float16"].includes(Je))throw new Error(`Invalid kv_cache_dtype: ${Je}. Should be one of: float32, float16`);const lt={dtype:Ge,kv_cache_dtype:Je},yt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Ge],st=`${S}${yt}.onnx`,Et=`${L.subfolder??""}/${st}`,at={...L.session_options};at.executionProviders??(at.executionProviders=Se);const vt=oe.free_dimension_overrides;vt?at.freeDimensionOverrides??(at.freeDimensionOverrides=vt):me.startsWith("webnn")&&!at.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const ct=(0,l.getModelFile)(x,Et,!0,L,b.apis.IS_NODE_ENV),Tt=L.use_external_data_format??oe.use_external_data_format;let Lt=[];if(Tt){let Pt;typeof Tt=="object"?Tt.hasOwnProperty(st)?Pt=Tt[st]:Tt.hasOwnProperty(S)?Pt=Tt[S]:Pt=!1:Pt=Tt;const Nt=+Pt;if(Nt>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Nt}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let tr=0;tr{const Sr=await(0,l.getModelFile)(x,Wr,!0,L,b.apis.IS_NODE_ENV);dn(Sr instanceof Uint8Array?{path:sr,data:Sr}:sr)}))}}else at.externalData!==void 0&&(Lt=at.externalData.map(async Pt=>{if(typeof Pt.data=="string"){const Nt=await(0,l.getModelFile)(x,Pt.data,!0,L);return{...Pt,data:Nt}}return Pt}));if(Lt.length>0){const Pt=await Promise.all(Lt);b.apis.IS_NODE_ENV||(at.externalData=Pt)}if(me==="webgpu"){const Pt=(0,s.getKeyValueShapes)(L.config,{prefix:"present"});if(Object.keys(Pt).length>0&&!(0,i.isONNXProxy)()){const Nt={};for(const tr in Pt)Nt[tr]="gpu-buffer";at.preferredOutputLocation=Nt}}return{buffer_or_path:await ct,session_options:at,session_config:lt}}async function B(x,S,L){return Object.fromEntries(await Promise.all(Object.keys(S).map(async oe=>{const{buffer_or_path:fe,session_options:me,session_config:Se}=await k(x,S[oe],L),De=await(0,i.createInferenceSession)(fe,me,Se);return[oe,De]})))}async function N(x,S,L){return Object.fromEntries(await Promise.all(Object.keys(S).map(async oe=>{const fe=await(0,l.getModelJSON)(x,S[oe],!1,L);return[oe,fe]})))}function J(x,S){const L=Object.create(null),oe=[];for(const Se of x.inputNames){const De=S[Se];if(!(De instanceof h.Tensor)){oe.push(Se);continue}L[Se]=(0,i.isONNXProxy)()?De.clone():De}if(oe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${oe.join(", ")}.`);const fe=Object.keys(S).length,me=x.inputNames.length;if(fe>me){let Se=Object.keys(S).filter(De=>!x.inputNames.includes(De));console.warn(`WARNING: Too many inputs were provided (${fe} > ${me}). The following inputs will be ignored: "${Se.join(", ")}".`)}return L}async function q(x,S){const L=J(x,S);try{const oe=Object.fromEntries(Object.entries(L).map(([me,Se])=>[me,Se.ort_tensor]));let fe=await x.run(oe);return fe=V(fe),fe}catch(oe){const fe=Object.fromEntries(Object.entries(L).map(([me,{type:Se,dims:De,data:Ge}])=>[me,{type:Se,dims:De,data:Ge}]));throw console.error(`An error occurred during model execution: "${oe}".`),console.error("Inputs given to model:",fe),oe}}function V(x){for(let S in x)(0,i.isONNXTensor)(x[S])?x[S]=new h.Tensor(x[S]):typeof x[S]=="object"&&V(x[S]);return x}function Y(x){if(x instanceof h.Tensor)return x;if(x.length===0)throw Error("items must be non-empty");if(Array.isArray(x[0])){if(x.some(S=>S.length!==x[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new h.Tensor("int64",BigInt64Array.from(x.flat().map(S=>BigInt(S))),[x.length,x[0].length])}else return new h.Tensor("int64",BigInt64Array.from(x.map(S=>BigInt(S))),[1,x.length])}function H(x){return new h.Tensor("bool",[x],[1])}async function Q(x,S){let{encoder_outputs:L,input_ids:oe,decoder_input_ids:fe,...me}=S;if(!L){const De=(0,a.pick)(S,x.sessions.model.inputNames);L=(await ie(x,De)).last_hidden_state}return me.input_ids=fe,me.encoder_hidden_states=L,x.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(me.encoder_attention_mask=S.attention_mask),await ae(x,me,!0)}async function ie(x,S){const L=x.sessions.model,oe=(0,a.pick)(S,L.inputNames);if(L.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds){if(!S.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");oe.inputs_embeds=await x.encode_text({input_ids:S.input_ids})}if(L.inputNames.includes("token_type_ids")&&!oe.token_type_ids){if(!oe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");oe.token_type_ids=(0,h.zeros_like)(oe.input_ids)}if(L.inputNames.includes("pixel_mask")&&!oe.pixel_mask){if(!oe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const fe=oe.pixel_values.dims;oe.pixel_mask=(0,h.ones)([fe[0],fe[2],fe[3]])}return await q(L,oe)}async function le(x,S){const L=await x.encode(S);return await x.decode(L)}async function ae(x,S,L=!1){const oe=x.sessions[L?"decoder_model_merged":"model"],{past_key_values:fe,...me}=S;if(oe.inputNames.includes("use_cache_branch")&&(me.use_cache_branch=H(!!fe)),oe.inputNames.includes("position_ids")&&me.attention_mask&&!me.position_ids){const De=["paligemma","gemma3_text","gemma3"].includes(x.config.model_type)?1:0;me.position_ids=_e(me,fe,De)}x.addPastKeyValues(me,fe);const Se=(0,a.pick)(me,oe.inputNames);return await q(oe,Se)}function we({modality_token_id:x,inputs_embeds:S,modality_features:L,input_ids:oe,attention_mask:fe}){const me=oe.tolist().map(Je=>Je.reduce((lt,yt,st)=>(yt==x&<.push(st),lt),[])),Se=me.reduce((Je,lt)=>Je+lt.length,0),De=L.dims[0];if(Se!==De)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${De}`);let Ge=0;for(let Je=0;Jeme.dims[1])){if(feDe==x.config.image_token_index)){const De=x.config.num_image_tokens;if(!De)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ge=me.dims[1]-(fe-De);L.input_ids=me.slice(null,[-Ge,null]),L.attention_mask=(0,h.ones)([1,fe+Ge])}}}return L}function He(x,S,L,oe){return L.past_key_values&&(S=S.map(fe=>[fe.at(-1)])),{...L,decoder_input_ids:Y(S)}}function Me(x,...S){return x.config.is_encoder_decoder?He(x,...S):ke(x,...S)}function K(x,S,L,oe){const fe=!!L.past_key_values;return oe.guidance_scale!==null&&oe.guidance_scale>1&&(fe?L.input_ids=(0,h.cat)([L.input_ids,L.input_ids],0):(L.input_ids=(0,h.cat)([L.input_ids,(0,h.full_like)(L.input_ids,BigInt(oe.pad_token_id))],0),L.attention_mask=(0,h.cat)([L.attention_mask,(0,h.full_like)(L.attention_mask,0n)],0))),(fe||!L.pixel_values)&&(L.pixel_values=(0,h.full)([0,0,3,384,384],1)),fe&&(L.images_seq_mask=new h.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),L.images_emb_mask=new h.Tensor("bool",new Array(0).fill(!1),[1,1,0])),L}class U extends o.Callable{constructor(L,oe,fe){super();re(this,"main_input_name","input_ids");re(this,"forward_params",["input_ids","attention_mask"]);this.config=L,this.sessions=oe,this.configs=fe;const me=E.get(this.constructor),Se=g.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Se){case T.DecoderOnly:this.can_generate=!0,this._forward=ae,this._prepare_inputs_for_generation=ke;break;case T.Seq2Seq:case T.Vision2Seq:case T.Musicgen:this.can_generate=!0,this._forward=Q,this._prepare_inputs_for_generation=He;break;case T.EncoderDecoder:this._forward=Q;break;case T.ImageTextToText:this.can_generate=!0,this._forward=X,this._prepare_inputs_for_generation=Me;break;case T.AudioTextToText:this.can_generate=!0,this._forward=ne,this._prepare_inputs_for_generation=Me;break;case T.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Me;break;case T.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=K;break;case T.AutoEncoder:this._forward=le;break;default:this._forward=ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var oe;const L=[];for(const fe of Object.values(this.sessions))(oe=fe==null?void 0:fe.handler)!=null&&oe.dispose&&L.push(fe.handler.dispose());return await Promise.all(L)}static async from_pretrained(L,{progress_callback:oe=null,config:fe=null,cache_dir:me=null,local_files_only:Se=!1,revision:De="main",model_file_name:Ge=null,subfolder:Je="onnx",device:lt=null,dtype:yt=null,use_external_data_format:st=null,session_options:Et={}}={}){let at={progress_callback:oe,config:fe,cache_dir:me,local_files_only:Se,revision:De,model_file_name:Ge,subfolder:Je,device:lt,dtype:yt,use_external_data_format:st,session_options:Et};const vt=E.get(this),ct=g.get(vt);fe=at.config=await s.AutoConfig.from_pretrained(L,at);let Tt;if(ct===T.DecoderOnly)Tt=await Promise.all([B(L,{model:at.model_file_name??"model"},at),N(L,{generation_config:"generation_config.json"},at)]);else if(ct===T.Seq2Seq||ct===T.Vision2Seq)Tt=await Promise.all([B(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at),N(L,{generation_config:"generation_config.json"},at)]);else if(ct===T.MaskGeneration)Tt=await Promise.all([B(L,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},at)]);else if(ct===T.EncoderDecoder)Tt=await Promise.all([B(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at)]);else if(ct===T.ImageTextToText){const Lt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};fe.is_encoder_decoder&&(Lt.model="encoder_model"),Tt=await Promise.all([B(L,Lt,at),N(L,{generation_config:"generation_config.json"},at)])}else if(ct===T.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};Tt=await Promise.all([B(L,Lt,at),N(L,{generation_config:"generation_config.json"},at)])}else if(ct===T.Musicgen)Tt=await Promise.all([B(L,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},at),N(L,{generation_config:"generation_config.json"},at)]);else if(ct===T.MultiModality)Tt=await Promise.all([B(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},at),N(L,{generation_config:"generation_config.json"},at)]);else if(ct===T.Phi3V)Tt=await Promise.all([B(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},at),N(L,{generation_config:"generation_config.json"},at)]);else if(ct===T.AutoEncoder)Tt=await Promise.all([B(L,{encoder_model:"encoder_model",decoder_model:"decoder_model"},at)]);else{if(ct!==T.EncoderOnly){const Lt=vt??(fe==null?void 0:fe.model_type);Lt!=="custom"&&console.warn(`Model type for '${Lt}' not found, assuming encoder-only architecture. Please report this at ${d.GITHUB_ISSUE_URL}.`)}Tt=await Promise.all([B(L,{model:at.model_file_name??"model"},at)])}return new this(fe,...Tt)}async _call(L){return await this.forward(L)}async forward(L){return await this._forward(this,L)}get generation_config(){var L;return((L=this.configs)==null?void 0:L.generation_config)??null}_get_logits_warper(L){const oe=new p.LogitsProcessorList;return L.temperature!==null&&L.temperature!==1&&oe.push(new p.TemperatureLogitsWarper(L.temperature)),L.top_k!==null&&L.top_k!==0&&oe.push(new p.TopKLogitsWarper(L.top_k)),L.top_p!==null&&L.top_p<1&&oe.push(new p.TopPLogitsWarper(L.top_p)),oe}_get_logits_processor(L,oe,fe=null){const me=new p.LogitsProcessorList;if(L.repetition_penalty!==null&&L.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(L.repetition_penalty)),L.no_repeat_ngram_size!==null&&L.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(L.no_repeat_ngram_size)),L.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(L.bad_words_ids,L.eos_token_id)),L.min_length!==null&&L.eos_token_id!==null&&L.min_length>0&&me.push(new p.MinLengthLogitsProcessor(L.min_length,L.eos_token_id)),L.min_new_tokens!==null&&L.eos_token_id!==null&&L.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(oe,L.min_new_tokens,L.eos_token_id)),L.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(L.forced_bos_token_id)),L.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(L.max_length,L.forced_eos_token_id)),L.begin_suppress_tokens!==null){const Se=oe>1||L.forced_bos_token_id===null?oe:oe+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se))}return L.guidance_scale!==null&&L.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(L.guidance_scale)),fe!==null&&me.extend(fe),me}_prepare_generation_config(L,oe,fe=u.GenerationConfig){const me={...this.config};for(const De of["decoder","generator","text_config"])De in me&&Object.assign(me,me[De]);const Se=new fe(me);return Object.assign(Se,this.generation_config??{}),L&&Object.assign(Se,L),oe&&Object.assign(Se,(0,a.pick)(oe,Object.getOwnPropertyNames(Se))),Se}_get_stopping_criteria(L,oe=null){const fe=new P.StoppingCriteriaList;return L.max_length!==null&&fe.push(new P.MaxLengthCriteria(L.max_length,this.config.max_position_embeddings??null)),L.eos_token_id!==null&&fe.push(new P.EosTokenCriteria(L.eos_token_id)),oe&&fe.extend(oe),fe}_validate_model_class(){if(!this.can_generate){const L=[vu,xu,bu,Mu],oe=E.get(this.constructor),fe=new Set,me=this.config.model_type;for(const De of L){const Ge=De.get(me);Ge&&fe.add(Ge[0])}let Se=`The current model class (${oe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw fe.size>0&&(Se+=` Please use the following class instead: ${[...fe].join(", ")}`),Error(Se)}}prepare_inputs_for_generation(...L){return this._prepare_inputs_for_generation(this,...L)}_update_model_kwargs_for_generation({generated_input_ids:L,outputs:oe,model_inputs:fe,is_encoder_decoder:me}){return fe.past_key_values=this.getPastKeyValues(oe,fe.past_key_values),fe.input_ids=new h.Tensor("int64",L.flat(),[L.length,1]),me||(fe.attention_mask=(0,h.cat)([fe.attention_mask,(0,h.ones)([fe.attention_mask.dims[0],1])],1)),fe.position_ids=null,fe}_prepare_model_inputs({inputs:L,bos_token_id:oe,model_kwargs:fe}){const me=(0,a.pick)(fe,this.forward_params),Se=this.main_input_name;if(Se in me){if(L)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[Se]=L;return{inputs_tensor:me[Se],model_inputs:me,model_input_name:Se}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:L,model_inputs:oe,model_input_name:fe,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:De,pixel_values:Ge,attention_mask:Je,...lt}=oe,yt=await this._prepare_inputs_embeds(oe);oe={...lt,...(0,a.pick)(yt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Se}=await ie(this,oe);if(me.guidance_scale!==null&&me.guidance_scale>1)Se=(0,h.cat)([Se,(0,h.full_like)(Se,0)],0),"attention_mask"in oe&&(oe.attention_mask=(0,h.cat)([oe.attention_mask,(0,h.zeros_like)(oe.attention_mask)],0));else if(oe.decoder_input_ids){const De=Y(oe.decoder_input_ids).dims[0];if(De!==Se.dims[0]){if(Se.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Se.dims[0]}) than the decoder inputs (${De}).`);Se=(0,h.cat)(Array.from({length:De},()=>Se),0)}}return oe.encoder_outputs=Se,oe}_prepare_decoder_input_ids_for_generation({batch_size:L,model_input_name:oe,model_kwargs:fe,decoder_start_token_id:me,bos_token_id:Se,generation_config:De}){let{decoder_input_ids:Ge,...Je}=fe;if(!(Ge instanceof h.Tensor)){if(Ge)Array.isArray(Ge[0])||(Ge=Array.from({length:L},()=>Ge));else if(me??(me=Se),this.config.model_type==="musicgen")Ge=Array.from({length:L*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==L)throw new Error(`\`decoder_start_token_id\` expcted to have length ${L} but got ${me.length}`);Ge=me}else Ge=Array.from({length:L},()=>[me]);Ge=Y(Ge)}return fe.decoder_attention_mask=(0,h.ones_like)(Ge),{input_ids:Ge,model_inputs:Je}}async generate({inputs:L=null,generation_config:oe=null,logits_processor:fe=null,stopping_criteria:me=null,streamer:Se=null,...De}){this._validate_model_class(),oe=this._prepare_generation_config(oe,De);let{inputs_tensor:Ge,model_inputs:Je,model_input_name:lt}=this._prepare_model_inputs({inputs:L,model_kwargs:De});const yt=this.config.is_encoder_decoder;yt&&("encoder_outputs"in Je||(Je=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ge,model_inputs:Je,model_input_name:lt,generation_config:oe})));let st;yt?{input_ids:st,model_inputs:Je}=this._prepare_decoder_input_ids_for_generation({batch_size:Je[lt].dims.at(0),model_input_name:lt,model_kwargs:Je,decoder_start_token_id:oe.decoder_start_token_id,bos_token_id:oe.bos_token_id,generation_config:oe}):st=Je[lt];let Et=st.dims.at(-1);oe.max_new_tokens!==null&&(oe.max_length=Et+oe.max_new_tokens);const at=this._get_logits_processor(oe,Et,fe),vt=this._get_stopping_criteria(oe,me),ct=Je[lt].dims.at(0),Tt=A.LogitsSampler.getSampler(oe),Lt=new Array(ct).fill(0),Qt=st.tolist();Se&&Se.put(Qt);let yr,Pt={};for(;;){if(Je=this.prepare_inputs_for_generation(Qt,Je,oe),yr=await this.forward(Je),oe.output_attentions&&oe.return_dict_in_generate){const Sr=this.getAttentions(yr);for(const $s in Sr)$s in Pt||(Pt[$s]=[]),Pt[$s].push(Sr[$s])}const sr=yr.logits.slice(null,-1,null),Wr=at(Qt,sr),dn=[];for(let Sr=0;SrSr))break;Je=this._update_model_kwargs_for_generation({generated_input_ids:dn,outputs:yr,model_inputs:Je,is_encoder_decoder:yt})}Se&&Se.end();const Nt=this.getPastKeyValues(yr,Je.past_key_values,!0),tr=new h.Tensor("int64",Qt.flat(),[Qt.length,Qt[0].length]);if(oe.return_dict_in_generate)return{sequences:tr,past_key_values:Nt,...Pt};for(const sr of Object.values(yr))sr.location==="gpu-buffer"&&sr.dispose();return tr}getPastKeyValues(L,oe,fe=!1){const me=Object.create(null);for(const Se in L)if(Se.startsWith("present")){const De=Se.replace("present","past_key_values"),Ge=Se.includes("encoder");if(Ge&&oe?me[De]=oe[De]:me[De]=L[Se],oe&&(!Ge||fe)){const Je=oe[De];Je.location==="gpu-buffer"&&Je.dispose()}}return me}getAttentions(L){const oe={};for(const fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in L)me.startsWith(fe)&&(fe in oe||(oe[fe]=[]),oe[fe].push(L[me]));return oe}addPastKeyValues(L,oe){var fe,me,Se;if(oe)Object.assign(L,oe);else{const De=this.sessions.decoder_model_merged??this.sessions.model,Ge=((fe=De==null?void 0:De.config)==null?void 0:fe.kv_cache_dtype)??"float32",Je=Ge==="float16"?new h.DataTypeMap.float16:[],lt=((Se=(me=L[this.main_input_name]??L.attention_mask)==null?void 0:me.dims)==null?void 0:Se[0])??1,yt=(0,s.getKeyValueShapes)(this.config,{batch_size:lt});for(const st in yt)L[st]=new h.Tensor(Ge,Je,yt[st])}}async encode_image({pixel_values:L}){const oe=(await q(this.sessions.vision_encoder,{pixel_values:L})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${oe.dims[1]}).`),this.config.num_image_tokens=oe.dims[1]),oe}async encode_text({input_ids:L}){return(await q(this.sessions.embed_tokens,{input_ids:L})).inputs_embeds}async encode_audio({audio_values:L}){return(await q(this.sessions.audio_encoder,{audio_values:L})).audio_features}}class pe{}class Pe extends pe{constructor({last_hidden_state:S,hidden_states:L=null,attentions:oe=null}){super(),this.last_hidden_state=S,this.hidden_states=L,this.attentions=oe}}class Te extends U{}class Ae extends Te{}class Ie extends Te{async _call(S){return new wr(await super._call(S))}}class Le extends Te{async _call(S){return new bt(await super._call(S))}}class Ne extends Te{async _call(S){return new pr(await super._call(S))}}class Ve extends Te{async _call(S){return new Cr(await super._call(S))}}class D extends U{}class Z extends D{}class z extends D{async _call(S){return new wr(await super._call(S))}}class ee extends D{async _call(S){return new bt(await super._call(S))}}class ce extends D{async _call(S){return new pr(await super._call(S))}}class be extends U{}class ve extends be{}class Re extends U{}class Fe extends Re{}class je extends Re{async _call(S){return new wr(await super._call(S))}}class Qe extends Re{async _call(S){return new bt(await super._call(S))}}class Xe extends Re{async _call(S){return new pr(await super._call(S))}}class ut extends Re{async _call(S){return new Cr(await super._call(S))}}class wt extends U{}class nr extends wt{}class jt extends wt{async _call(S){return new wr(await super._call(S))}}class dr extends wt{async _call(S){return new bt(await super._call(S))}}class ds extends wt{async _call(S){return new pr(await super._call(S))}}class Fs extends wt{async _call(S){return new Cr(await super._call(S))}}class Dr extends U{}class cs extends Dr{}class Os extends Dr{async _call(S){return new wr(await super._call(S))}}class jr extends Dr{async _call(S){return new bt(await super._call(S))}}class dt extends Dr{async _call(S){return new pr(await super._call(S))}}class qr extends Dr{async _call(S){return new Cr(await super._call(S))}}class Ur extends U{}class us extends Ur{}class xs extends Ur{async _call(S){return new wr(await super._call(S))}}class Ts extends Ur{async _call(S){return new bt(await super._call(S))}}class Es extends Ur{async _call(S){return new pr(await super._call(S))}}class Ds extends Ur{async _call(S){return new Cr(await super._call(S))}}class mr extends U{}class Be extends mr{}class et extends mr{async _call(S){return new wr(await super._call(S))}}class it extends mr{async _call(S){return new bt(await super._call(S))}}class rr extends mr{async _call(S){return new pr(await super._call(S))}}class zt extends mr{async _call(S){return new Cr(await super._call(S))}}class Ir extends U{}class ps extends Ir{}class hs extends Ir{async _call(S){return new wr(await super._call(S))}}class Er extends Ir{async _call(S){return new bt(await super._call(S))}}class ms extends Ir{async _call(S){return new pr(await super._call(S))}}class _s extends Ir{async _call(S){return new Cr(await super._call(S))}}class Qr extends U{}class Ps extends Qr{}class qs extends Qr{async _call(S){return new bt(await super._call(S))}}class Qs extends Qr{async _call(S){return new pr(await super._call(S))}}class Xs extends Qr{async _call(S){return new Cr(await super._call(S))}}class Js extends Qr{async _call(S){return new wr(await super._call(S))}}class fs extends U{}class Ys extends fs{}class Zs extends fs{async _call(S){return new wr(await super._call(S))}}class en extends fs{async _call(S){return new bt(await super._call(S))}}class Lr extends fs{async _call(S){return new pr(await super._call(S))}}class Cs extends U{}class br extends Cs{}class Ls extends Cs{async _call(S){return new wr(await super._call(S))}}class zs extends Cs{async _call(S){return new bt(await super._call(S))}}class Ar extends Cs{async _call(S){return new Cr(await super._call(S))}}class Xr extends U{}class Tn extends Xr{}class zr extends Xr{async _call(S){return new wr(await super._call(S))}}class En extends Xr{async _call(S){return new bt(await super._call(S))}}class Bs extends Xr{async _call(S){return new pr(await super._call(S))}}class Fr extends Xr{async _call(S){return new Cr(await super._call(S))}}class Jr extends U{}class cr extends Jr{}class _r extends Jr{async _call(S){return new wr(await super._call(S))}}class Rs extends Jr{async _call(S){return new bt(await super._call(S))}}class Pn extends Jr{async _call(S){return new Cr(await super._call(S))}}class Ss extends U{}class Cn extends Ss{}class ue extends Ss{async _call(S){return new bt(await super._call(S))}}class F extends Ss{async _call(S){return new Cr(await super._call(S))}}class j extends Ss{async _call(S){return new wr(await super._call(S))}}class te extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class de extends te{}class he extends te{}class Ce extends U{}class We extends Ce{}class qe extends Ce{}class Ke extends U{}class Ze extends Ke{}class ht extends Ke{}class Ct extends U{}class kt extends Ct{}class Wt extends Ct{}class Ot extends Ct{async _call(S){return new bt(await super._call(S))}}class Ut extends U{}class vr extends Ut{}class fr extends Ut{}class Yr extends Ut{async _call(S){return new bt(await super._call(S))}}class xr extends Ut{}class gs extends U{}class Gt extends gs{}class Zt extends gs{}class gr extends U{}class Zr extends gr{}class ws extends gr{}class Ht extends U{}class ur extends Ht{}class Rt extends Ht{async _call(S){return new wr(await super._call(S))}}class Jt extends Ht{async _call(S){return new bt(await super._call(S))}}class qt extends Ht{async _call(S){return new pr(await super._call(S))}}class er extends Ht{async _call(S){return new Cr(await super._call(S))}}class ir extends U{}class tn extends ir{}class rn extends ir{async _call(S){return new wr(await super._call(S))}}class La extends ir{async _call(S){return new bt(await super._call(S))}}class Vi extends ir{async _call(S){return new pr(await super._call(S))}}class za extends ir{async _call(S){return new Cr(await super._call(S))}}class ys extends U{}class Ba extends ys{}class Ra extends ys{async _call(S){return new wr(await super._call(S))}}class Sn extends ys{async _call(S){return new bt(await super._call(S))}}class Na extends ys{async _call(S){return new pr(await super._call(S))}}class Wi extends ys{async _call(S){return new Cr(await super._call(S))}}class Gi extends U{}class ja extends Gi{}class Ua extends Gi{}class Gn extends U{constructor(){super(...arguments);re(this,"requires_attention_mask",!1);re(this,"main_input_name","input_features");re(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Va extends Gn{}class Ki extends Gn{_prepare_generation_config(S,L){return super._prepare_generation_config(S,L,y.WhisperGenerationConfig)}_retrieve_init_tokens(S){const L=[S.decoder_start_token_id];let oe=S.language;const fe=S.task;if(S.is_multilingual){oe||(console.warn("No language specified - defaulting to English (en)."),oe="en");const Se=`<|${(0,$.whisper_language_to_code)(oe)}|>`;L.push(S.lang_to_id[Se]),L.push(S.task_to_id[fe??"transcribe"])}else if(oe||fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!S.return_timestamps&&S.no_timestamps_token_id&&L.at(-1)!==S.no_timestamps_token_id?L.push(S.no_timestamps_token_id):S.return_timestamps&&L.at(-1)===S.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),L.pop()),L.filter(me=>me!=null)}async generate({inputs:S=null,generation_config:L=null,logits_processor:oe=null,stopping_criteria:fe=null,...me}){L=this._prepare_generation_config(L,me);const Se=me.decoder_input_ids??this._retrieve_init_tokens(L);if(L.return_timestamps&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.WhisperTimeStampLogitsProcessor(L,Se))),L.begin_suppress_tokens&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se.length))),L.return_token_timestamps){if(!L.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");L.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),L.output_attentions=!0,L.return_dict_in_generate=!0}const De=await super.generate({inputs:S,generation_config:L,logits_processor:oe,decoder_input_ids:Se,...me});return L.return_token_timestamps&&(De.token_timestamps=this._extract_token_timestamps(De,L.alignment_heads,L.num_frames)),De}_extract_token_timestamps(S,L,oe=null,fe=.02){if(!S.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");oe==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let me=this.config.median_filter_width;me===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),me=7);const Se=S.cross_attentions,De=Array.from({length:this.config.decoder_layers},(vt,ct)=>(0,h.cat)(Se.map(Tt=>Tt[ct]),2)),Ge=(0,h.stack)(L.map(([vt,ct])=>{if(vt>=De.length)throw new Error(`Layer index ${vt} is out of bounds for cross attentions (length ${De.length}).`);return oe?De[vt].slice(null,ct,null,[0,oe]):De[vt].slice(null,ct)})).transpose(1,0,2,3),[Je,lt]=(0,h.std_mean)(Ge,-2,0,!0),yt=Ge.clone();for(let vt=0;vtTt[tr+1]-Tt[tr]),yr=(0,a.mergeArrays)([1],Qt).map(Nt=>!!Nt),Pt=[];for(let Nt=0;Ntst.findIndex(Et=>Et==me)),Ge=De.every(st=>st===-1),Je=De.every(st=>st!==-1);if(!Ge&&!Je)throw new Error("Every input should contain either 0 or 1 image token.");if(Ge)return{inputs_embeds:S,attention_mask:fe};const lt=[],yt=[];for(let st=0;stArray.from({length:S.dims[0]},Qt=>Array.from({length:S.dims[1]},yr=>1))),at=L?L.tolist():[],vt=oe?oe.tolist():[];let ct=0,Tt=0;for(let Lt=0;Ltst[Lt][or]==1),Pt=Qt.reduce((Kt,or,cn)=>(or==Ge&&Kt.push(cn),Kt),[]).map(Kt=>Qt[Kt+1]),Nt=Pt.filter(Kt=>Kt==Se).length,tr=Pt.filter(Kt=>Kt==De).length;let sr=[],Wr=0,dn=Nt,Zl=tr;for(let Kt=0;KtMs>Wr&&Dn==Se),cn=Qt.findIndex((Dn,Ms)=>Ms>Wr&&Dn==De),On=dn>0&&or!==-1?or:Qt.length+1,Pi=Zl>0&&cn!==-1?cn:Qt.length+1;let sd,Pu,Cu,Su;On0?(0,f.max)(sr.at(-1))[0]+1:0;sr.push(Array.from({length:3*ku},(Dn,Ms)=>fb+Ms%ku));const Iu=ku+fb,id=Sx*$u*nd,$x=Array.from({length:id},(Dn,Ms)=>Iu+Math.floor(Ms/($u*nd))),kx=Array.from({length:id},(Dn,Ms)=>Iu+Math.floor(Ms/nd)%$u),Ix=Array.from({length:id},(Dn,Ms)=>Iu+Ms%nd);sr.push([$x,kx,Ix].flat()),Wr=sd+id}if(Wr0?(0,f.max)(sr.at(-1))[0]+1:0,or=Qt.length-Wr;sr.push(Array.from({length:3*or},(cn,On)=>Kt+On%or))}const Sr=sr.reduce((Kt,or)=>Kt+or.length,0),$s=new Array(Sr);let Eu=0;for(let Kt=0;Kt<3;++Kt)for(let or=0;oryt[ct%yt.length]),at=Array.from({length:st[0]},(vt,ct)=>(0,f.max)(yt.subarray(st[1]*ct,st[1]*(ct+1)))[0]+1n+BigInt(st[1]));return[new h.Tensor("int64",Et,[3,...st]),new h.Tensor("int64",at,[at.length,1])]}else{const[yt,st]=S.dims,Et=BigInt64Array.from({length:3*yt*st},(at,vt)=>BigInt(Math.floor(vt%st/yt)));return[new h.Tensor("int64",Et,[3,...S.dims]),(0,h.zeros)([yt,1])]}}async encode_image({pixel_values:S,image_grid_thw:L}){return(await q(this.sessions.vision_encoder,{pixel_values:S,grid_thw:L})).image_features}_merge_input_ids_with_image_features(S){return R({image_token_id:this.config.image_token_id,...S})}prepare_inputs_for_generation(S,L,oe){if(L.attention_mask&&!L.position_ids)if(!L.past_key_values)[L.position_ids,L.rope_deltas]=this.get_rope_index(L.input_ids,L.image_grid_thw,L.video_grid_thw,L.attention_mask);else{L.pixel_values=null;const fe=BigInt(Object.values(L.past_key_values)[0].dims.at(-2)),me=L.rope_deltas.map(Se=>fe+Se);L.position_ids=(0,h.stack)([me,me,me],0)}return L}}class fi extends U{}class Do extends fi{}class Lo extends fi{}class gi extends U{}class zo extends gi{}class Bo extends gi{}class wi extends U{}class Ro extends wi{}class No extends wi{}class yi extends U{}class jo extends yi{}class Uo extends yi{}class Mi extends U{}class Vo extends Mi{}class Wo extends Mi{}class bi extends U{}class Go extends bi{}class Ko extends bi{async _call(S){return new bt(await super._call(S))}}class vi extends U{}class Ho extends vi{}class qo extends vi{async _call(S){return new bt(await super._call(S))}}class Qo extends U{}class Xo extends Qo{}class Jo extends U{}class dl extends Jo{}class cl extends Jo{async _call(S){return new bt(await super._call(S))}}class ul extends U{}class pl extends ul{}class Yo extends U{}class hl extends Yo{}class ml extends Yo{async _call(S){return new bt(await super._call(S))}}class _l extends U{}class fl extends _l{}class Zo extends U{}class gl extends Zo{}class wl extends Zo{async _call(S){return new bt(await super._call(S))}}class yl extends U{}class Ml extends yl{async _call(S){return new mb(await super._call(S))}}class ea extends U{}class bl extends ea{}class vl extends ea{async _call(S){return new bt(await super._call(S))}}class ta extends U{}class xl extends ta{}class Tl extends ta{async _call(S){return new bt(await super._call(S))}}class ra extends U{}class El extends ra{}class Pl extends ra{}class sa extends U{}class Cl extends sa{}class Sl extends sa{}class na extends U{}class $l extends na{}class kl extends na{async _call(S){return new bt(await super._call(S))}}class xi extends U{}class Il extends xi{}class Al extends xi{async _call(S){return new oa(await super._call(S))}}class ia extends xi{async _call(S){return new Fl(await super._call(S))}}class oa extends pe{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class Fl extends pe{constructor({logits:S,pred_boxes:L,pred_masks:oe}){super(),this.logits=S,this.pred_boxes=L,this.pred_masks=oe}}class aa extends U{}class Ol extends aa{}class Dl extends aa{async _call(S){return new Ll(await super._call(S))}}class Ll extends pe{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class la extends U{}class zl extends la{}class Bl extends la{async _call(S){return new Rl(await super._call(S))}}class Rl extends oa{}class da extends U{}class ca extends da{}class c extends da{async _call(S){return new bt(await super._call(S))}}class m extends U{}class v extends m{}class C extends m{async _call(S){return new bt(await super._call(S))}}class I extends U{}class W extends I{}class se extends I{async _call(S){return new bt(await super._call(S))}}class ge extends U{}class Ee extends ge{}class ze extends ge{async _call(S){return new bt(await super._call(S))}}class Ye extends ge{}class ot extends U{}class gt extends ot{}class Bt extends ot{}class Pr extends U{}class an extends Pr{}class qw extends Pr{}class Qw extends U{}class Xw extends Qw{}class Nl extends U{}class Jw extends Nl{}class Yw extends Nl{}class Zw extends Nl{}class ey extends U{}class ty extends ey{}class ry extends U{}class sy extends ry{}class ny extends U{}class iy extends ny{}class eu extends U{}class oy extends eu{}class ay extends eu{}class tu extends U{}class ly extends tu{}class dy extends tu{}class cy extends U{}class uy extends cy{}class ru extends U{}class py extends ru{}class hy extends ru{async _call(S){return new bt(await super._call(S))}}class su extends U{}class my extends su{}class _y extends su{async _call(S){return new bt(await super._call(S))}}class nu extends U{}class fy extends nu{}class gy extends nu{async _call(S){return new bt(await super._call(S))}}class iu extends U{}class wy extends iu{}class yy extends iu{async _call(S){return new bt(await super._call(S))}}class My extends U{}class by extends My{}class ou extends U{}class vy extends ou{}class xy extends ou{async _call(S){return new Ty(await super._call(S))}}class Ty extends pe{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class Ey extends U{}class Py extends Ey{async get_image_embeddings({pixel_values:S}){return await ie(this,{pixel_values:S})}async forward(S){if((!S.image_embeddings||!S.image_positional_embeddings)&&(S={...S,...await this.get_image_embeddings(S)}),!S.input_labels&&S.input_points){const oe=S.input_points.dims.slice(0,-1),fe=oe.reduce((me,Se)=>me*Se,1);S.input_labels=new h.Tensor("int64",new BigInt64Array(fe).fill(1n),oe)}const L={image_embeddings:S.image_embeddings,image_positional_embeddings:S.image_positional_embeddings};return S.input_points&&(L.input_points=S.input_points),S.input_labels&&(L.input_labels=S.input_labels),S.input_boxes&&(L.input_boxes=S.input_boxes),await q(this.sessions.prompt_encoder_mask_decoder,L)}async _call(S){return new Cy(await super._call(S))}}class Cy extends pe{constructor({iou_scores:S,pred_masks:L}){super(),this.iou_scores=S,this.pred_masks=L}}class au extends U{}class Sy extends au{}class $y extends au{}class lu extends U{}class ky extends lu{}class Iy extends lu{}class ln extends U{}class Ay extends ln{}class Fy extends ln{async _call(S){return new Fn(await super._call(S))}}class Oy extends ln{async _call(S){return new bt(await super._call(S))}}class Dy extends ln{async _call(S){return new pr(await super._call(S))}}class du extends U{}class Ly extends du{}class zy extends du{async _call(S){return new pr(await super._call(S))}}class By extends U{}class Ry extends By{}class jl extends U{}class Ny extends jl{}class jy extends jl{async _call(S){return new Fn(await super._call(S))}}class Uy extends jl{async _call(S){return new bt(await super._call(S))}}class ua extends U{}class Vy extends ua{}class Wy extends ua{async _call(S){return new Fn(await super._call(S))}}class Gy extends ua{async _call(S){return new bt(await super._call(S))}}class Ky extends ua{async _call(S){return new pr(await super._call(S))}}class Ul extends U{}class Hy extends Ul{}class qy extends Ul{async _call(S){return new Fn(await super._call(S))}}class Qy extends Ul{async _call(S){return new bt(await super._call(S))}}class hx extends U{}class Xy extends ln{}class Jy extends ln{async _call(S){return new Fn(await super._call(S))}}class Yy extends ln{async _call(S){return new bt(await super._call(S))}}class Ti extends U{}class Zy extends Ti{}class eM extends Ti{async _call(S){return new Fn(await super._call(S))}}class tM extends Ti{async _call(S){return new bt(await super._call(S))}}class rM extends Ti{async _call(S){return new hb(await super._call(S))}}class sM extends Ti{async _call(S){return new pr(await super._call(S))}}class nM extends U{}class iM extends nM{}class Vl extends U{}class mx extends Vl{}class oM extends Vl{}class aM extends Vl{async generate_speech(S,L,{threshold:oe=.5,minlenratio:fe=0,maxlenratio:me=20,vocoder:Se=null}={}){const De={input_ids:S},{encoder_outputs:Ge,encoder_attention_mask:Je}=await ie(this,De),lt=Ge.dims[1]/this.config.reduction_factor,yt=Math.floor(lt*me),st=Math.floor(lt*fe),Et=this.config.num_mel_bins;let at=[],vt=null,ct=null,Tt=0;for(;;){++Tt;const yr=H(!!ct);let Pt;ct?Pt=ct.output_sequence_out:Pt=new h.Tensor("float32",new Float32Array(Et),[1,1,Et]);let Nt={use_cache_branch:yr,output_sequence:Pt,encoder_attention_mask:Je,speaker_embeddings:L,encoder_hidden_states:Ge};this.addPastKeyValues(Nt,vt),ct=await q(this.sessions.decoder_model_merged,Nt),vt=this.getPastKeyValues(ct,vt);const{prob:tr,spectrum:sr}=ct;if(at.push(sr),Tt>=st&&(Array.from(tr.data).filter(Wr=>Wr>=oe).length>0||Tt>=yt))break}const Lt=(0,h.cat)(at),{waveform:Qt}=await q(Se.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Qt}}}class lM extends U{constructor(){super(...arguments);re(this,"main_input_name","spectrogram")}}class dM extends U{}class cM extends dM{}class cu extends U{}class uM extends cu{}class pM extends cu{}class uu extends U{}class hM extends uu{}class mM extends uu{}class pu extends U{}class _M extends pu{}class fM extends pu{}class Wl extends U{}class gM extends Wl{}class wM extends Wl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"text_model"})}}class yM extends Wl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"audio_model"})}}class MM extends U{}class hu extends MM{async _call(S){return new _b(await super._call(S))}}class Gl extends U{}class _x extends Gl{}class bM extends Gl{}class vM extends Gl{}class mu extends U{}class xM extends mu{}class TM extends mu{}class _u extends U{}class EM extends _u{}class PM extends _u{async _call(S){return new bt(await super._call(S))}}class fu extends U{}class fx extends fu{}class gx extends fu{}class gu extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(L){const[oe,fe]=L.dims,me=this.config.decoder.num_codebooks,Se=fe-me;let De=0;for(let lt=0;lt0&&Et<=Se&&(L.data[De++]=L.data[lt])}const Ge=Math.floor(oe/me),Je=De/(Ge*me);return new h.Tensor(L.type,L.data.slice(0,De),[Ge,me,Je])}prepare_inputs_for_generation(L,oe,fe){let me=structuredClone(L);for(let De=0;De=Ge&&(me[De][Ge]=BigInt(this.config.decoder.pad_token_id));return fe.guidance_scale!==null&&fe.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,oe,fe)}async generate(L){const oe=await super.generate(L),fe=this._apply_and_filter_by_delay_pattern_mask(oe).unsqueeze_(0),{audio_values:me}=await q(this.sessions.encodec_decode,{audio_codes:fe});return me}}class Kl extends U{}class CM extends Kl{}class SM extends Kl{async _call(S){return new bt(await super._call(S))}}class $M extends Kl{}class Hl extends U{}class kM extends Hl{}class IM extends Hl{async _call(S){return new bt(await super._call(S))}}class AM extends Hl{}class ql extends U{}class FM extends ql{}class OM extends ql{async _call(S){return new bt(await super._call(S))}}class DM extends ql{}class Ql extends U{}class LM extends Ql{}class zM extends Ql{async _call(S){return new bt(await super._call(S))}}class BM extends Ql{}class RM extends U{}class NM extends RM{}class jM extends U{}class UM extends jM{constructor(...L){super(...L);re(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(L){const oe=this._generation_mode??"text";let fe;if(oe==="text"||!L.past_key_values){const Je=this.sessions.prepare_inputs_embeds,lt=(0,a.pick)(L,Je.inputNames);fe=await q(Je,lt)}else{const Je=this.sessions.gen_img_embeds,lt=(0,a.pick)({image_ids:L.input_ids},Je.inputNames);fe=await q(Je,lt)}const me={...L,...fe},Se=await ae(this,me),De=this.sessions[oe==="text"?"lm_head":"gen_head"];if(!De)throw new Error(`Unable to find "${De}" generation head`);const Ge=await q(De,(0,a.pick)(Se,De.inputNames));return{...fe,...Se,...Ge}}async generate(L){return this._generation_mode="text",super.generate(L)}async generate_images(L){this._generation_mode="image";const oe=(L.inputs??L[this.main_input_name]).dims[1],me=(await super.generate(L)).slice(null,[oe,null]),Se=this.sessions.image_decode,{decoded_image:De}=await q(Se,{generated_tokens:me}),Ge=De.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Je=[];for(const lt of Ge){const yt=w.RawImage.fromTensor(lt);Je.push(yt)}return Je}}class VM extends pe{constructor({char_logits:S,bpe_logits:L,wp_logits:oe}){super(),this.char_logits=S,this.bpe_logits=L,this.wp_logits=oe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class WM extends U{}class GM extends WM{async _call(S){return new VM(await super._call(S))}}class wu extends U{}class KM extends wu{}class HM extends wu{}class yu extends U{}class qM extends yu{}class QM extends yu{}class XM extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class JM extends XM{_merge_input_ids_with_audio_features(S){const L=S.audio_features.dims.at(-1),oe=S.audio_features.view(-1,L);return O({audio_token_id:this.config.ignore_index,...S,audio_features:oe})}}class Xl extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class YM extends pe{constructor({audio_codes:S}){super(),this.audio_codes=S}}class ZM extends pe{constructor({audio_values:S}){super(),this.audio_values=S}}class e0 extends Xl{async encode(S){return new YM(await q(this.sessions.encoder_model,S))}async decode(S){return new ZM(await q(this.sessions.decoder_model,S))}}class t0 extends Xl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class r0 extends Xl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class Jl extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class s0 extends pe{constructor({audio_codes:S}){super(),this.audio_codes=S}}class n0 extends pe{constructor({audio_values:S}){super(),this.audio_values=S}}class i0 extends Jl{async encode(S){return new s0(await q(this.sessions.encoder_model,S))}async decode(S){return new n0(await q(this.sessions.decoder_model,S))}}class o0 extends Jl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class a0 extends Jl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class Yl extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class l0 extends Yl{async encode(S){return await q(this.sessions.encoder_model,S)}async decode(S){return await q(this.sessions.decoder_model,S)}}class d0 extends Yl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class c0 extends Yl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class It{static async from_pretrained(S,{progress_callback:L=null,config:oe=null,cache_dir:fe=null,local_files_only:me=!1,revision:Se="main",model_file_name:De=null,subfolder:Ge="onnx",device:Je=null,dtype:lt=null,use_external_data_format:yt=null,session_options:st={}}={}){const Et={progress_callback:L,config:oe,cache_dir:fe,local_files_only:me,revision:Se,model_file_name:De,subfolder:Ge,device:Je,dtype:lt,use_external_data_format:yt,session_options:st};if(Et.config=await s.AutoConfig.from_pretrained(S,Et),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const at=Et.config.model_type;for(const vt of this.MODEL_CLASS_MAPPINGS){let ct=vt.get(at);if(!ct){for(const Tt of vt.values())if(Tt[0]===at){ct=Tt;break}if(!ct)continue}return await ct[1].from_pretrained(S,Et)}if(this.BASE_IF_FAIL)return L0.has(at)||console.warn(`Unknown model class "${at}", attempting to construct from base class.`),await U.from_pretrained(S,Et);throw Error(`Unsupported model type: ${at}`)}}re(It,"MODEL_CLASS_MAPPINGS",null),re(It,"BASE_IF_FAIL",!1);const wx=new Map([["bert",["BertModel",Ae]],["modernbert",["ModernBertModel",Z]],["nomic_bert",["NomicBertModel",ve]],["roformer",["RoFormerModel",Fe]],["electra",["ElectraModel",cs]],["esm",["EsmModel",Ys]],["convbert",["ConvBertModel",nr]],["camembert",["CamembertModel",us]],["deberta",["DebertaModel",Be]],["deberta-v2",["DebertaV2Model",ps]],["mpnet",["MPNetModel",Tn]],["albert",["AlbertModel",Cn]],["distilbert",["DistilBertModel",Ps]],["roberta",["RobertaModel",ur]],["xlm",["XLMModel",tn]],["xlm-roberta",["XLMRobertaModel",Ba]],["clap",["ClapModel",gM]],["clip",["CLIPModel",Zi]],["clipseg",["CLIPSegModel",nn]],["chinese_clip",["ChineseCLIPModel",rl]],["siglip",["SiglipModel",Ya]],["jina_clip",["JinaCLIPModel",sl]],["mobilebert",["MobileBertModel",br]],["squeezebert",["SqueezeBertModel",cr]],["wav2vec2",["Wav2Vec2Model",Ay]],["wav2vec2-bert",["Wav2Vec2BertModel",Hy]],["unispeech",["UniSpeechModel",Ny]],["unispeech-sat",["UniSpeechSatModel",Vy]],["hubert",["HubertModel",Xy]],["wavlm",["WavLMModel",Zy]],["audio-spectrogram-transformer",["ASTModel",ja]],["vits",["VitsModel",hu]],["pyannote",["PyAnnoteModel",Ly]],["wespeaker-resnet",["WeSpeakerResNetModel",Ry]],["detr",["DetrModel",Il]],["rt_detr",["RTDetrModel",Ol]],["table-transformer",["TableTransformerModel",zl]],["vit",["ViTModel",Go]],["ijepa",["IJepaModel",Ho]],["pvt",["PvtModel",dl]],["vit_msn",["ViTMSNModel",hl]],["vit_mae",["ViTMAEModel",pl]],["groupvit",["GroupViTModel",fl]],["fastvit",["FastViTModel",gl]],["mobilevit",["MobileViTModel",bl]],["mobilevitv2",["MobileViTV2Model",xl]],["owlvit",["OwlViTModel",El]],["owlv2",["Owlv2Model",Cl]],["beit",["BeitModel",$l]],["deit",["DeiTModel",ca]],["hiera",["HieraModel",v]],["convnext",["ConvNextModel",py]],["convnextv2",["ConvNextV2Model",my]],["dinov2",["Dinov2Model",fy]],["dinov2_with_registers",["Dinov2WithRegistersModel",wy]],["resnet",["ResNetModel",W]],["swin",["SwinModel",Ee]],["swin2sr",["Swin2SRModel",gt]],["donut-swin",["DonutSwinModel",uy]],["yolos",["YolosModel",vy]],["dpt",["DPTModel",an]],["glpn",["GLPNModel",ly]],["hifigan",["SpeechT5HifiGan",lM]],["efficientnet",["EfficientNetModel",EM]],["decision_transformer",["DecisionTransformerModel",NM]],["patchtst",["PatchTSTForPrediction",KM]],["patchtsmixer",["PatchTSMixerForPrediction",qM]],["mobilenet_v1",["MobileNetV1Model",CM]],["mobilenet_v2",["MobileNetV2Model",kM]],["mobilenet_v3",["MobileNetV3Model",FM]],["mobilenet_v4",["MobileNetV4Model",LM]],["maskformer",["MaskFormerModel",oy]],["mgp-str",["MgpstrForSceneTextRecognition",GM]],["style_text_to_speech_2",["StyleTextToSpeech2Model",iM]]]),yx=new Map([["t5",["T5Model",de]],["longt5",["LongT5Model",We]],["mt5",["MT5Model",Ze]],["bart",["BartModel",kt]],["mbart",["MBartModel",vr]],["marian",["MarianModel",Sy]],["whisper",["WhisperModel",Va]],["m2m_100",["M2M100Model",ky]],["blenderbot",["BlenderbotModel",Gt]],["blenderbot-small",["BlenderbotSmallModel",Zr]]]),Mx=new Map([["mimi",["MimiModel",e0]],["dac",["DacModel",i0]],["snac",["SnacModel",l0]]]),bx=new Map([["bloom",["BloomModel",Ro]],["jais",["JAISModel",ro]],["gpt2",["GPT2Model",ol]],["gptj",["GPTJModel",lo]],["gpt_bigcode",["GPTBigCodeModel",ll]],["gpt_neo",["GPTNeoModel",no]],["gpt_neox",["GPTNeoXModel",al]],["codegen",["CodeGenModel",In]],["llama",["LlamaModel",ri]],["exaone",["ExaoneModel",mo]],["olmo",["OlmoModel",fo]],["olmo2",["Olmo2Model",wo]],["mobilellm",["MobileLLMModel",_t]],["granite",["GraniteModel",yo]],["cohere",["CohereModel",bo]],["gemma",["GemmaModel",xo]],["gemma2",["Gemma2Model",Eo]],["gemma3_text",["Gemma3Model",Co]],["helium",["HeliumModel",po]],["glm",["GlmModel",ho]],["openelm",["OpenELMModel",$o]],["qwen2",["Qwen2Model",Io]],["phi",["PhiModel",Do]],["phi3",["Phi3Model",zo]],["mpt",["MptModel",jo]],["opt",["OPTModel",Vo]],["mistral",["MistralModel",uM]],["starcoder2",["Starcoder2Model",hM]],["falcon",["FalconModel",_M]],["stablelm",["StableLmModel",xM]]]),Mu=new Map([["speecht5",["SpeechT5ForSpeechToText",oM]],["whisper",["WhisperForConditionalGeneration",Ki]],["lite-whisper",["LiteWhisperForConditionalGeneration",Wa]],["moonshine",["MoonshineForConditionalGeneration",Ga]]]),u0=new Map([["speecht5",["SpeechT5ForTextToSpeech",aM]]]),p0=new Map([["vits",["VitsModel",hu]],["musicgen",["MusicgenForConditionalGeneration",gu]]]),h0=new Map([["bert",["BertForSequenceClassification",Le]],["modernbert",["ModernBertForSequenceClassification",ee]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",jr]],["esm",["EsmForSequenceClassification",en]],["convbert",["ConvBertForSequenceClassification",dr]],["camembert",["CamembertForSequenceClassification",Ts]],["deberta",["DebertaForSequenceClassification",it]],["deberta-v2",["DebertaV2ForSequenceClassification",Er]],["mpnet",["MPNetForSequenceClassification",En]],["albert",["AlbertForSequenceClassification",ue]],["distilbert",["DistilBertForSequenceClassification",qs]],["roberta",["RobertaForSequenceClassification",Jt]],["xlm",["XLMForSequenceClassification",La]],["xlm-roberta",["XLMRobertaForSequenceClassification",Sn]],["bart",["BartForSequenceClassification",Ot]],["mbart",["MBartForSequenceClassification",Yr]],["mobilebert",["MobileBertForSequenceClassification",zs]],["squeezebert",["SqueezeBertForSequenceClassification",Rs]]]),m0=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",ce]],["roformer",["RoFormerForTokenClassification",Xe]],["electra",["ElectraForTokenClassification",dt]],["esm",["EsmForTokenClassification",Lr]],["convbert",["ConvBertForTokenClassification",ds]],["camembert",["CamembertForTokenClassification",Es]],["deberta",["DebertaForTokenClassification",rr]],["deberta-v2",["DebertaV2ForTokenClassification",ms]],["mpnet",["MPNetForTokenClassification",Bs]],["distilbert",["DistilBertForTokenClassification",Qs]],["roberta",["RobertaForTokenClassification",qt]],["xlm",["XLMForTokenClassification",Vi]],["xlm-roberta",["XLMRobertaForTokenClassification",Na]]]),bu=new Map([["t5",["T5ForConditionalGeneration",he]],["longt5",["LongT5ForConditionalGeneration",qe]],["mt5",["MT5ForConditionalGeneration",ht]],["bart",["BartForConditionalGeneration",Wt]],["mbart",["MBartForConditionalGeneration",fr]],["marian",["MarianMTModel",$y]],["m2m_100",["M2M100ForConditionalGeneration",Iy]],["blenderbot",["BlenderbotForConditionalGeneration",Zt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ws]]]),vu=new Map([["bloom",["BloomForCausalLM",No]],["gpt2",["GPT2LMHeadModel",Yn]],["jais",["JAISLMHeadModel",so]],["gptj",["GPTJForCausalLM",kn]],["gpt_bigcode",["GPTBigCodeForCausalLM",co]],["gpt_neo",["GPTNeoForCausalLM",io]],["gpt_neox",["GPTNeoXForCausalLM",oo]],["codegen",["CodeGenForCausalLM",Vr]],["llama",["LlamaForCausalLM",uo]],["exaone",["ExaoneForCausalLM",mt]],["olmo",["OlmoForCausalLM",go]],["olmo2",["Olmo2ForCausalLM",li]],["mobilellm",["MobileLLMForCausalLM",_o]],["granite",["GraniteForCausalLM",Mo]],["cohere",["CohereForCausalLM",vo]],["gemma",["GemmaForCausalLM",To]],["gemma2",["Gemma2ForCausalLM",Po]],["gemma3_text",["Gemma3ForCausalLM",So]],["helium",["HeliumForCausalLM",ni]],["glm",["GlmForCausalLM",ft]],["openelm",["OpenELMForCausalLM",ko]],["qwen2",["Qwen2ForCausalLM",Ao]],["phi",["PhiForCausalLM",Lo]],["phi3",["Phi3ForCausalLM",Bo]],["mpt",["MptForCausalLM",Uo]],["opt",["OPTForCausalLM",Wo]],["mbart",["MBartForCausalLM",xr]],["mistral",["MistralForCausalLM",pM]],["starcoder2",["Starcoder2ForCausalLM",mM]],["falcon",["FalconForCausalLM",fM]],["trocr",["TrOCRForCausalLM",cM]],["stablelm",["StableLmForCausalLM",TM]],["phi3_v",["Phi3VForCausalLM",Ns]]]),vx=new Map([["multi_modality",["MultiModalityCausalLM",UM]]]),_0=new Map([["bert",["BertForMaskedLM",Ie]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",je]],["electra",["ElectraForMaskedLM",Os]],["esm",["EsmForMaskedLM",Zs]],["convbert",["ConvBertForMaskedLM",jt]],["camembert",["CamembertForMaskedLM",xs]],["deberta",["DebertaForMaskedLM",et]],["deberta-v2",["DebertaV2ForMaskedLM",hs]],["mpnet",["MPNetForMaskedLM",zr]],["albert",["AlbertForMaskedLM",j]],["distilbert",["DistilBertForMaskedLM",Js]],["roberta",["RobertaForMaskedLM",Rt]],["xlm",["XLMWithLMHeadModel",rn]],["xlm-roberta",["XLMRobertaForMaskedLM",Ra]],["mobilebert",["MobileBertForMaskedLM",Ls]],["squeezebert",["SqueezeBertForMaskedLM",_r]]]),f0=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",ut]],["electra",["ElectraForQuestionAnswering",qr]],["convbert",["ConvBertForQuestionAnswering",Fs]],["camembert",["CamembertForQuestionAnswering",Ds]],["deberta",["DebertaForQuestionAnswering",zt]],["deberta-v2",["DebertaV2ForQuestionAnswering",_s]],["mpnet",["MPNetForQuestionAnswering",Fr]],["albert",["AlbertForQuestionAnswering",F]],["distilbert",["DistilBertForQuestionAnswering",Xs]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",za]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Wi]],["mobilebert",["MobileBertForQuestionAnswering",Ar]],["squeezebert",["SqueezeBertForQuestionAnswering",Pn]]]),xu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",qi]],["idefics3",["Idefics3ForConditionalGeneration",Hn]],["smolvlm",["SmolVLMForConditionalGeneration",qn]]]),g0=new Map([["llava",["LlavaForConditionalGeneration",Kn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Ha]],["moondream1",["Moondream1ForConditionalGeneration",qa]],["florence2",["Florence2ForConditionalGeneration",Qi]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Oo]],["idefics3",["Idefics3ForConditionalGeneration",Hn]],["smolvlm",["SmolVLMForConditionalGeneration",qn]],["paligemma",["PaliGemmaForConditionalGeneration",Ji]]]),w0=new Map([["ultravox",["UltravoxModel",JM]]]),xx=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",qi]]]),y0=new Map([["vit",["ViTForImageClassification",Ko]],["ijepa",["IJepaForImageClassification",qo]],["pvt",["PvtForImageClassification",cl]],["vit_msn",["ViTMSNForImageClassification",ml]],["fastvit",["FastViTForImageClassification",wl]],["mobilevit",["MobileViTForImageClassification",vl]],["mobilevitv2",["MobileViTV2ForImageClassification",Tl]],["beit",["BeitForImageClassification",kl]],["deit",["DeiTForImageClassification",c]],["hiera",["HieraForImageClassification",C]],["convnext",["ConvNextForImageClassification",hy]],["convnextv2",["ConvNextV2ForImageClassification",_y]],["dinov2",["Dinov2ForImageClassification",gy]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",yy]],["resnet",["ResNetForImageClassification",se]],["swin",["SwinForImageClassification",ze]],["segformer",["SegformerForImageClassification",bM]],["efficientnet",["EfficientNetForImageClassification",PM]],["mobilenet_v1",["MobileNetV1ForImageClassification",SM]],["mobilenet_v2",["MobileNetV2ForImageClassification",IM]],["mobilenet_v3",["MobileNetV3ForImageClassification",OM]],["mobilenet_v4",["MobileNetV4ForImageClassification",zM]]]),M0=new Map([["detr",["DetrForObjectDetection",Al]],["rt_detr",["RTDetrForObjectDetection",Dl]],["table-transformer",["TableTransformerForObjectDetection",Bl]],["yolos",["YolosForObjectDetection",xy]]]),b0=new Map([["owlvit",["OwlViTForObjectDetection",Pl]],["owlv2",["Owlv2ForObjectDetection",Sl]],["grounding-dino",["GroundingDinoForObjectDetection",by]]]),Ei=new Map([["detr",["DetrForSegmentation",ia]],["clipseg",["CLIPSegForImageSegmentation",eo]]]),v0=new Map([["segformer",["SegformerForSemanticSegmentation",vM]],["sapiens",["SapiensForSemanticSegmentation",Jw]],["swin",["SwinForSemanticSegmentation",Ye]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",$M]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",AM]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",DM]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",BM]]]),x0=new Map([["detr",["DetrForSegmentation",ia]],["maskformer",["MaskFormerForInstanceSegmentation",ay]]]),T0=new Map([["sam",["SamModel",Py]]]),E0=new Map([["wav2vec2",["Wav2Vec2ForCTC",Fy]],["wav2vec2-bert",["Wav2Vec2BertForCTC",qy]],["unispeech",["UniSpeechForCTC",jy]],["unispeech-sat",["UniSpeechSatForCTC",Wy]],["wavlm",["WavLMForCTC",eM]],["hubert",["HubertForCTC",Jy]]]),P0=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Oy]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Qy]],["unispeech",["UniSpeechForSequenceClassification",Uy]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Gy]],["wavlm",["WavLMForSequenceClassification",tM]],["hubert",["HubertForSequenceClassification",Yy]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ua]]]),C0=new Map([["wavlm",["WavLMForXVector",rM]]]),S0=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ky]],["wavlm",["WavLMForAudioFrameClassification",sM]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Dy]],["pyannote",["PyAnnoteForAudioFrameClassification",zy]]]),$0=new Map([["vitmatte",["VitMatteForImageMatting",Ml]]]),Tx=new Map([["patchtst",["PatchTSTForPrediction",HM]],["patchtsmixer",["PatchTSMixerForPrediction",QM]]]),k0=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Bt]]]),I0=new Map([["dpt",["DPTForDepthEstimation",qw]],["depth_anything",["DepthAnythingForDepthEstimation",Xw]],["glpn",["GLPNForDepthEstimation",dy]],["sapiens",["SapiensForDepthEstimation",Yw]],["depth_pro",["DepthProForDepthEstimation",ty]],["metric3d",["Metric3DForDepthEstimation",sy]],["metric3dv2",["Metric3Dv2ForDepthEstimation",iy]]]),A0=new Map([["sapiens",["SapiensForNormalEstimation",Zw]]]),F0=new Map([["vitpose",["VitPoseForPoseEstimation",Xo]]]),O0=new Map([["clip",["CLIPVisionModelWithProjection",Qn]],["siglip",["SiglipVisionModel",el]],["jina_clip",["JinaCLIPVisionModel",il]]]),D0=[[wx,T.EncoderOnly],[yx,T.EncoderDecoder],[bx,T.DecoderOnly],[Mx,T.AutoEncoder],[h0,T.EncoderOnly],[m0,T.EncoderOnly],[bu,T.Seq2Seq],[Mu,T.Seq2Seq],[vu,T.DecoderOnly],[vx,T.MultiModality],[_0,T.EncoderOnly],[f0,T.EncoderOnly],[xu,T.Vision2Seq],[g0,T.ImageTextToText],[w0,T.AudioTextToText],[y0,T.EncoderOnly],[Ei,T.EncoderOnly],[x0,T.EncoderOnly],[v0,T.EncoderOnly],[$0,T.EncoderOnly],[Tx,T.EncoderOnly],[k0,T.EncoderOnly],[I0,T.EncoderOnly],[A0,T.EncoderOnly],[F0,T.EncoderOnly],[M0,T.EncoderOnly],[b0,T.EncoderOnly],[T0,T.MaskGeneration],[E0,T.EncoderOnly],[P0,T.EncoderOnly],[u0,T.Seq2Seq],[p0,T.EncoderOnly],[C0,T.EncoderOnly],[S0,T.EncoderOnly],[O0,T.EncoderOnly]];for(const[x,S]of D0)for(const[L,oe]of x.values())g.set(L,S),E.set(oe,L),M.set(L,oe);const Ex=[["MusicgenForConditionalGeneration",gu,T.Musicgen],["Phi3VForCausalLM",Ns,T.Phi3V],["CLIPTextModelWithProjection",Ja,T.EncoderOnly],["SiglipTextModel",Za,T.EncoderOnly],["JinaCLIPTextModel",nl,T.EncoderOnly],["ClapTextModelWithProjection",wM,T.EncoderOnly],["ClapAudioModelWithProjection",yM,T.EncoderOnly],["DacEncoderModel",o0,T.EncoderOnly],["DacDecoderModel",a0,T.EncoderOnly],["MimiEncoderModel",t0,T.EncoderOnly],["MimiDecoderModel",r0,T.EncoderOnly],["SnacEncoderModel",d0,T.EncoderOnly],["SnacDecoderModel",c0,T.EncoderOnly]];for(const[x,S,L]of Ex)g.set(x,L),E.set(S,x),M.set(x,S);const L0=new Map([["modnet",Ei],["birefnet",Ei],["isnet",Ei],["ben",Ei]]);for(const[x,S]of L0.entries())S.set(x,["PreTrainedModel",U]),g.set(x,T.EncoderOnly),E.set(U,x),M.set(x,U);class Tu extends It{}re(Tu,"MODEL_CLASS_MAPPINGS",D0.map(S=>S[0])),re(Tu,"BASE_IF_FAIL",!0);class z0 extends It{}re(z0,"MODEL_CLASS_MAPPINGS",[h0]);class B0 extends It{}re(B0,"MODEL_CLASS_MAPPINGS",[m0]);class R0 extends It{}re(R0,"MODEL_CLASS_MAPPINGS",[bu]);class N0 extends It{}re(N0,"MODEL_CLASS_MAPPINGS",[Mu]);class j0 extends It{}re(j0,"MODEL_CLASS_MAPPINGS",[u0]);class U0 extends It{}re(U0,"MODEL_CLASS_MAPPINGS",[p0]);class V0 extends It{}re(V0,"MODEL_CLASS_MAPPINGS",[vu]);class W0 extends It{}re(W0,"MODEL_CLASS_MAPPINGS",[_0]);class G0 extends It{}re(G0,"MODEL_CLASS_MAPPINGS",[f0]);class K0 extends It{}re(K0,"MODEL_CLASS_MAPPINGS",[xu]);class H0 extends It{}re(H0,"MODEL_CLASS_MAPPINGS",[y0]);class q0 extends It{}re(q0,"MODEL_CLASS_MAPPINGS",[Ei]);class Q0 extends It{}re(Q0,"MODEL_CLASS_MAPPINGS",[v0]);class X0 extends It{}re(X0,"MODEL_CLASS_MAPPINGS",[x0]);class J0 extends It{}re(J0,"MODEL_CLASS_MAPPINGS",[M0]);class Y0 extends It{}re(Y0,"MODEL_CLASS_MAPPINGS",[b0]);class Z0 extends It{}re(Z0,"MODEL_CLASS_MAPPINGS",[T0]);class eb extends It{}re(eb,"MODEL_CLASS_MAPPINGS",[E0]);class tb extends It{}re(tb,"MODEL_CLASS_MAPPINGS",[P0]);class rb extends It{}re(rb,"MODEL_CLASS_MAPPINGS",[C0]);class sb extends It{}re(sb,"MODEL_CLASS_MAPPINGS",[S0]);class nb extends It{}re(nb,"MODEL_CLASS_MAPPINGS",[xx]);class ib extends It{}re(ib,"MODEL_CLASS_MAPPINGS",[$0]);class ob extends It{}re(ob,"MODEL_CLASS_MAPPINGS",[k0]);class ab extends It{}re(ab,"MODEL_CLASS_MAPPINGS",[I0]);class lb extends It{}re(lb,"MODEL_CLASS_MAPPINGS",[A0]);class db extends It{}re(db,"MODEL_CLASS_MAPPINGS",[F0]);class cb extends It{}re(cb,"MODEL_CLASS_MAPPINGS",[O0]);class ub extends It{}re(ub,"MODEL_CLASS_MAPPINGS",[g0]);class pb extends It{}re(pb,"MODEL_CLASS_MAPPINGS",[w0]);class Px extends pe{constructor({logits:S,past_key_values:L,encoder_outputs:oe,decoder_attentions:fe=null,cross_attentions:me=null}){super(),this.logits=S,this.past_key_values=L,this.encoder_outputs=oe,this.decoder_attentions=fe,this.cross_attentions=me}}class bt extends pe{constructor({logits:S,...L}){super(),this.logits=S;const oe=Object.values(L);oe.length>0&&(this.attentions=oe)}}class hb extends pe{constructor({logits:S,embeddings:L}){super(),this.logits=S,this.embeddings=L}}class pr extends pe{constructor({logits:S}){super(),this.logits=S}}class wr extends pe{constructor({logits:S}){super(),this.logits=S}}class Cr extends pe{constructor({start_logits:S,end_logits:L}){super(),this.start_logits=S,this.end_logits=L}}class Fn extends pe{constructor({logits:S}){super(),this.logits=S}}class Cx extends pe{constructor({logits:S,past_key_values:L}){super(),this.logits=S,this.past_key_values=L}}class mb extends pe{constructor({alphas:S}){super(),this.alphas=S}}class _b extends pe{constructor({waveform:S,spectrogram:L}){super(),this.waveform=S,this.spectrogram=L}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,d=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;p{t.r(r),t.d(r,{AutoFeatureExtractor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class o{static async from_pretrained(l,d={}){const p=await(0,i.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,d),u=p.feature_extractor_type,h=n[u];if(!h)throw new Error(`Unknown feature_extractor_type: '${u}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new h(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),o=t("./src/models/image_processors.js");class a{static async from_pretrained(d,p={}){const u=await(0,i.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,p),h=u.image_processor_type??u.feature_extractor_type;let w=o[h];return w||(h!==void 0&&console.warn(`Image processor type '${h}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),w=n.ImageProcessor),new w(u)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>d});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),o=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class d{static async from_pretrained(u,h={}){const w=await(0,i.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,h),{image_processor_type:f,feature_extractor_type:P,processor_class:A}=w;if(A&&o[A])return o[A].from_pretrained(u,h);if(!f&&!P)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const b={};if(f){const $=a[f];if(!$)throw new Error(`Unknown image_processor_type: '${f}'.`);b.image_processor=new $(w)}if(P){const $=a[P];if($)b.image_processor=new $(w);else{const T=l[P];if(!T)throw new Error(`Unknown feature_extractor_type: '${P}'.`);b.feature_extractor=new T(w)}}const y={};return new n.Processor(y,b)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,i.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,i.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,i.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,d,p){let u;const h=a.length-l;if(h>0)if(d==="rand_trunc"){const w=Math.floor(Math.random()*(h+1));a=a.subarray(w,w+l),u=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${d}" not implemented`);else{if(h<0){let w=new Float64Array(l);if(w.set(a),p==="repeat")for(let f=a.length;f{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var d;const l=(d=this.size)==null?void 0:d.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[u,h]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(u,h,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends i{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>i});var s=t("./src/models/encodec/feature_extraction_encodec.js");class i extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>o,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const d=await super._call(l),p=[d.pixel_values.dims[0],64,64],u=(0,i.full)(p,1n);return{...d,pixel_mask:u}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class o extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(a,l,d,p={}){const[u,h,w]=l;let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(w).fill(f));let P=this.image_std;Array.isArray(P)||(P=new Array(w).fill(f));const A=f.map((b,y)=>-b/P[y]);return super.pad_image(a,l,d,{center:!0,constant_values:A,...p})}}class n extends i{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super(o),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const d=[1,l,a.length/l];return{input_values:new i.Tensor("float32",a,d)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>o.DacFeatureExtractor,EncodecFeatureExtractor:()=>i.EncodecFeatureExtractor,ImageFeatureExtractor:()=>P.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>h.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>w.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>f.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),i=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),o=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),u=t("./src/models/speecht5/feature_extraction_speecht5.js"),h=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),w=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),f=t("./src/models/whisper/feature_extraction_whisper.js"),P=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{constructor(l,d){super(l,d);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:u,task_prompts_with_input:h}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(h??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const d=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))d.push(this.task_prompts_without_inputs.get(p));else{for(const[u,h]of this.task_prompts_with_input)if(p.includes(u)){d.push(h.replaceAll("{input}",p).replaceAll(u,""));break}d.length!==l.length&&d.push(p)}return d}post_process_generation(l,d,p){const u=this.tasks_answer_post_processing_type.get(d)??"pure_text";l=l.replaceAll("","").replaceAll("","");let h;switch(u){case"pure_text":h=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const w=u==="ocr"?"quad_boxes":"bboxes",f=l.matchAll(this.regexes[w]),P=[],A=[];for(const[b,y,...$]of f)P.push(y?y.trim():P.at(-1)??""),A.push($.map((T,g)=>(Number(T)+.5)/this.size_per_bin*p[g%2]));h={labels:P,[w]:A};break;default:throw new Error(`Task "${d}" (of type "${u}") not yet implemented.`)}return{[d]:h}}async _call(l,d=null,p={}){if(!l&&!d)throw new Error("Either text or images must be provided");const u=await this.image_processor(l,p),h=d?this.tokenizer(d,p):{};return{...u,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),d=l.pixel_values.dims,p=(0,i.ones)([d[0],d[2],d[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/image_processors_utils.js");function a(d,p){const h=d.dims.at(-1)-1,w=d.tolist();w.fill(!1,0,1),w.fill(!1,h);const f=p.tolist();return w.map((P,A)=>P?A:null).filter(P=>P!==null).map(P=>f[P])}class l extends s.Processor{async _call(p,u,h={}){const w=p?await this.image_processor(p,h):{};return{...u?this.tokenizer(u,h):{},...w}}post_process_grounded_object_detection(p,u,{box_threshold:h=.25,text_threshold:w=.25,target_sizes:f=null}={}){const{logits:P,pred_boxes:A}=p,b=P.dims[0];if(f!==null&&f.length!==b)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const y=P.dims.at(1),$=P.sigmoid(),T=$.max(-1).tolist(),g=A.tolist().map(E=>E.map(k=>(0,o.center_to_corners_format)(k))),M=[];for(let E=0;EV.map((Y,H)=>Y*k[(H+1)%2])));const B=T[E],N=[],J=[],q=[];for(let V=0;V{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[d,p]=a.dims.slice(-2);const u=p/d;return p>=d?(p=Math.ceil(p/l)*l,d=Math.floor(p/u),d=Math.ceil(d/l)*l):(d=Math.ceil(d/l)*l,p=Math.floor(d*u),p=Math.ceil(p/l)*l),{height:d,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:d=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let u=[],h=[],w=[];const f=[],P=[];for(const E of p){let k=await Promise.all(E.map(J=>this.preprocess(J)));f.push(...k.map(J=>J.original_size)),P.push(...k.map(J=>J.reshaped_input_size)),k.forEach(J=>J.pixel_values.unsqueeze_(0));const{longest_edge:B}=this.max_image_size;let N;if(l??this.do_image_splitting){let J=new Array(k.length),q=new Array(k.length);N=await Promise.all(k.map(async(V,Y)=>{const H=this.get_resize_for_vision_encoder(V.pixel_values,B),Q=await(0,i.interpolate_4d)(V.pixel_values,{size:[H.height,H.width]}),{frames:ie,num_splits_h:le,num_splits_w:ae}=await this.split_image(Q,this.max_image_size);return J[Y]=le,q[Y]=ae,(0,i.cat)(ie,0)})),h.push(J),w.push(q)}else{const J=[B,B];N=await Promise.all(k.map(q=>(0,i.interpolate_4d)(q.pixel_values,{size:J}))),h.push(new Array(k.length).fill(0)),w.push(new Array(k.length).fill(0))}u.push((0,i.cat)(N,0))}const A=u.length,[b,y,$,T]=u[0].dims;let g,M;if(A===1)g=u[0].unsqueeze_(0),M=(0,i.full)([A,b,$,T],!0);else{const E=Math.max(...u.map(N=>N.dims.at(0)));M=(0,i.full)([A,E,$,T],!0);const k=M.data,B=E*$*T;for(let N=0;Nd||w>p){f=Math.ceil(h/d),P=Math.ceil(w/p);const A=Math.ceil(h/f),b=Math.ceil(w/P);for(let T=0;T{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var o=t("./src/utils/core.js");function a(u,h,w,f,P,A){let b="";for(let y=0;y`+P.repeat(u);b+=` +`}return b+=` +${f}${A}`+P.repeat(u)+`${f}`,b}function l(u,h,w,f){return`${h}${f}`+w.repeat(u)+`${h}`}function d(u,h,w,f,P,A){return u===0&&h===0?l(w,f,P,A):a(w,u,h,f,P,A)}class p extends s.Processor{constructor(){super(...arguments);re(this,"fake_image_token","");re(this,"image_token","");re(this,"global_img_token","")}async _call(w,f=null,P={}){P.return_row_col_info??(P.return_row_col_info=!0);let A;f&&(A=await this.image_processor(f,P)),Array.isArray(w)||(w=[w]);const b=A.rows??[new Array(w.length).fill(0)],y=A.cols??[new Array(w.length).fill(0)],$=this.config.image_seq_len,T=[],g=[];for(let E=0;Ed(Y,N[H],$,this.fake_image_token,this.image_token,this.global_img_token)),q=k.split(this.image_token);if(q.length===0)throw new Error("The image token should be present in the text.");let V=q[0];for(let Y=0;Y{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>i.BitImageProcessor,CLIPFeatureExtractor:()=>o.CLIPFeatureExtractor,CLIPImageProcessor:()=>o.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>d.DetrFeatureExtractor,DetrImageProcessor:()=>d.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>h.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>w.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>P.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>b.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>y.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>$.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>T.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>T.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>g.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>g.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>E.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>E.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>k.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>k.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>B.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>B.MobileViTImageProcessor,NougatImageProcessor:()=>N.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>J.Owlv2ImageProcessor,Phi3VImageProcessor:()=>V.Phi3VImageProcessor,PvtImageProcessor:()=>Y.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Q.RTDetrImageProcessor,SamImageProcessor:()=>ie.SamImageProcessor,SegformerFeatureExtractor:()=>le.SegformerFeatureExtractor,SegformerImageProcessor:()=>le.SegformerImageProcessor,SiglipImageProcessor:()=>ae.SiglipImageProcessor,SmolVLMImageProcessor:()=>we.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>R.Swin2SRImageProcessor,VLMImageProcessor:()=>A.VLMImageProcessor,ViTFeatureExtractor:()=>O.ViTFeatureExtractor,ViTImageProcessor:()=>O.ViTImageProcessor,VitMatteImageProcessor:()=>G.VitMatteImageProcessor,VitPoseImageProcessor:()=>ne.VitPoseImageProcessor,YolosFeatureExtractor:()=>X.YolosFeatureExtractor,YolosImageProcessor:()=>X.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),i=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),o=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),d=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),h=t("./src/models/efficientnet/image_processing_efficientnet.js"),w=t("./src/models/glpn/image_processing_glpn.js"),f=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),P=t("./src/models/idefics3/image_processing_idefics3.js"),A=t("./src/models/janus/image_processing_janus.js"),b=t("./src/models/jina_clip/image_processing_jina_clip.js"),y=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),$=t("./src/models/mask2former/image_processing_mask2former.js"),T=t("./src/models/maskformer/image_processing_maskformer.js"),g=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),E=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),k=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),B=t("./src/models/mobilevit/image_processing_mobilevit.js"),N=t("./src/models/nougat/image_processing_nougat.js"),J=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),V=t("./src/models/phi3_v/image_processing_phi3_v.js"),Y=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Q=t("./src/models/rt_detr/image_processing_rt_detr.js"),ie=t("./src/models/sam/image_processing_sam.js"),le=t("./src/models/segformer/image_processing_segformer.js"),ae=t("./src/models/siglip/image_processing_siglip.js"),we=t("./src/models/smolvlm/image_processing_smolvlm.js"),R=t("./src/models/swin2sr/image_processing_swin2sr.js"),O=t("./src/models/vit/image_processing_vit.js"),G=t("./src/models/vitmatte/image_processing_vitmatte.js"),ne=t("./src/models/vitpose/image_processing_vitpose.js"),X=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super({do_pad:!0,pad_size:{width:o.image_size,height:o.image_size},...o}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(o,a,l,d){return super.pad_image(o,a,l,{constant_values:this.constant_values,center:!0,...d})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>d});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class d extends s.Processor{constructor(u,h){super(u,h),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(u,{images:h=null,chat_template:w="default"}={}){h?Array.isArray(h)||(h=[h]):h=await Promise.all(u.filter(N=>N.images).flatMap(N=>N.images).map(N=>l.RawImage.read(N)));const f=this.tokenizer,P=f.apply_chat_template(u,{tokenize:!1,add_generation_prompt:!0,chat_template:w}),A=N=>f.encode(N,{add_special_tokens:!1}),b=P.split(this.image_tag),y=b.length-1;if(h.length!==y)throw new Error(`Number of images provided (${h.length}) does not match number of "${this.image_tag}" image tags (${y})`);const[$,T,g]=f.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=A(b[0]),E=new Array(M.length).fill(!1);for(let N=1;N0){const N=await this.image_processor(h);return N.pixel_values.unsqueeze_(0),{...B,...N}}return B}}re(d,"image_processor_class",i.AutoImageProcessor),re(d,"tokenizer_class",n.AutoTokenizer),re(d,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){const{resize_mode:a,fill_color:l,interpolation:d,size:p,...u}=o,h=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},w=d==="bicubic"?3:2;super({...u,size:h,resample:w,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{async _call(l=null,d=null,p={}){if(!l&&!d)throw new Error("Either text or images must be provided");const u=l?this.tokenizer(l,p):{},h=d?await this.image_processor(d,p):{};return{...u,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>i});var s=t("./src/models/maskformer/image_processing_maskformer.js");class i extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends i{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,u){if(!a.hasOwnProperty(u))throw new Error(`Format ${u} is not supported.`);const[h,w]=a[u],f=this[h].bind(this),[P,A]=p.dims,b=[],y=[],$=p.tolist();for(let g=0;g0?k.reduce((N,J)=>N*J,1):0;y.push(E),b.push(B)}return[f(y),b]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}batch_decode([p,u,h]){const[w,f]=this._decode_helper(p,"char"),[P,A]=this._decode_helper(u,"bpe"),[b,y]=this._decode_helper(h,"wp"),$=[],T=[];for(let g=0;g{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new i.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>i});var s=t("./src/models/donut/image_processing_donut.js");class i extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>i});var s=t("./src/models/owlvit/image_processing_owlvit.js");class i extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const o="";function a(d,p,u,h,w){return`${h.repeat(u*w)}${p}${d} +`}class l extends s.Processor{async _call(p,u=null,h={}){u||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),u=""),Array.isArray(p)||(p=[p]),Array.isArray(u)||(u=[u]);const w=this.tokenizer.bos_token,f=this.image_processor.config.image_seq_length;let P;u.some(y=>y.includes(o))?P=u.map(y=>{const $=y.replaceAll(o,o.repeat(f)),T=$.lastIndexOf(o),g=T===-1?0:T+o.length;return $.slice(0,g)+w+$.slice(g)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),P=u.map(y=>a(y,w,f,o,p.length)));const A=this.tokenizer(P,h);return{...await this.image_processor(p,h),...A}}}re(l,"tokenizer_class",n.AutoTokenizer),re(l,"image_processor_class",i.AutoImageProcessor),re(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");const n=336,o=[2,3],{ceil:a,floor:l,sqrt:d}=Math;class p extends s.ImageProcessor{constructor(h){super({...h,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=h.num_crops}calc_num_image_tokens_from_image_size(h,w){const{num_img_tokens:f}=this.config;return l((l(w/n)*l(h/n)+1)*f+1+(l(w/n)+1)*d(f))}get_resize_output_image_size(h,w){const f=this._num_crops,[P,A]=h.size;let b=P/A,y=1;for(;y*Math.ceil(y/b)<=f;)y+=1;y-=1;const $=Math.floor(y*336),T=Math.floor($/b);return[$,T]}pad_image(h,w,f,P={}){const[A,b]=w,y=n*a(A/n),$=n*a(b/n),T=[1,1,1].map((g,M)=>(g-this.image_mean[M])/this.image_std[M]);return super.pad_image(h,w,{width:$,height:y},{center:!0,constant_values:T,...P})}async _call(h,{num_crops:w=null}={}){if(this._num_crops=w??(w=this.config.num_crops),w<4||d(w)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(h)||(h=[h]);const f=h.length,P=await Promise.all(h.map(E=>this.preprocess(E))),A=P.map(E=>E.original_size),b=P.map(E=>E.reshaped_input_size),y=[];for(const{pixel_values:E}of P){E.unsqueeze_(0);const[k,B]=E.dims.slice(-2),N=await(0,i.interpolate_4d)(E,{size:[n,n],mode:"bicubic"});if(w>0){const J=[],q=d(w),V=l(B/q),Y=l(k/q);for(let Q=0;QE.map(k=>n*a(k/n))),g=new i.Tensor("int64",T.flat(),[f,2]),M=T.map(([E,k])=>this.calc_num_image_tokens_from_image_size(k,E));return{pixel_values:$,original_sizes:A,reshaped_input_sizes:b,image_sizes:g,num_img_tokens:M}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const o="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,u=null,{padding:h=!0,truncation:w=!0,num_crops:f=null}={}){Array.isArray(p)||(p=[p]);let P,A;if(u){A=await this.image_processor(u,{num_crops:f});const{num_img_tokens:b}=A,y=p.map((T,g)=>T.split(a).join(o.repeat(b[g])));P=this.tokenizer(y,{padding:h,truncation:w});const $=this.tokenizer.model.convert_tokens_to_ids([o])[0];P.input_ids.map_(T=>T==$?-T:T)}else P=this.tokenizer(p);return{...P,...A}}}re(l,"image_processor_class",i.AutoImageProcessor),re(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>i.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>h.PaliGemmaProcessor,Phi3VProcessor:()=>u.Phi3VProcessor,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,Qwen2VLProcessor:()=>f.Qwen2VLProcessor,SamProcessor:()=>P.SamProcessor,SmolVLMProcessor:()=>A.SmolVLMProcessor,SpeechT5Processor:()=>b.SpeechT5Processor,UltravoxProcessor:()=>y.UltravoxProcessor,VLChatProcessor:()=>o.VLChatProcessor,Wav2Vec2Processor:()=>$.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>T.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>g.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),i=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),o=t("./src/models/janus/processing_janus.js"),a=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),u=t("./src/models/phi3_v/processing_phi3_v.js"),h=t("./src/models/paligemma/processing_paligemma.js"),w=t("./src/models/pyannote/processing_pyannote.js"),f=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),P=t("./src/models/sam/processing_sam.js"),A=t("./src/models/smolvlm/processing_smolvlm.js"),b=t("./src/models/speecht5/processing_speecht5.js"),y=t("./src/models/ultravox/processing_ultravox.js"),$=t("./src/models/wav2vec2/processing_wav2vec2.js"),T=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),g=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const d=[1,1,l.length];return{input_values:new i.Tensor("float32",l,d)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,d){const p=d/this.samples_to_frames(d)/this.config.sampling_rate,u=[];for(const h of l.tolist()){const w=[];let f=-1;for(let P=0;P({id:P,start:A*p,end:b*p,confidence:y/(b-A)})))}return u}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),i=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}re(n,"feature_extractor_class",i.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:d,original_sizes:p,reshaped_input_sizes:u}=await super._call(a,...l);let h=d;const{temporal_patch_size:w,merge_size:f,patch_size:P}=this.config;h.dims[0]===1&&(h=(0,i.cat)(Array.from({length:w},()=>h),0));const A=h.dims[0]/w,b=h.dims[1],y=Math.floor(h.dims[2]/P),$=Math.floor(h.dims[3]/P),T=h.view(A,w,b,Math.floor(y/f),f,P,Math.floor($/f),f,P).permute(0,3,6,4,7,2,1,5,8).view(A*y*$,b*w*P*P),g=new i.Tensor("int64",[A,y,$],[1,3]);return{pixel_values:T,image_grid_thw:g,original_sizes:p,reshaped_input_sizes:u}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class o extends s.Processor{async _call(l,d=null,...p){Array.isArray(l)||(l=[l]);let u,h;if(d&&(u=await this.image_processor(d),h=u.image_grid_thw),h){let f=this.image_processor.config.merge_size**2,P=0;const A=h.tolist();l=l.map(b=>{for(;b.includes("<|image_pad|>");){const y=Number(A[P++].reduce(($,T)=>$*T,1n));b=b.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(y/f)))}return b.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...u}}}re(o,"image_processor_class",i.AutoImageProcessor),re(o,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...o){return(0,s.post_process_object_detection)(...o)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{reshape_input_points(l,d,p,u=!1){l=structuredClone(l);let h=(0,i.calculateDimensions)(l);if(h.length===3)u||(h=[1,...h]),l=[l];else if(h.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let w=0;wu!==d.dims[h]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:d=null,input_labels:p=null,input_boxes:u=null}={}){const h=await super._call(l);if(d&&(h.input_points=this.reshape_input_points(d,h.original_sizes,h.reshaped_input_sizes)),p){if(!h.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");h.input_labels=this.add_input_labels(p,h.input_points)}return u&&(h.input_boxes=this.reshape_input_points(u,h.original_sizes,h.reshaped_input_sizes,!0)),h}async post_process_masks(l,d,p,{mask_threshold:u=0,binarize:h=!0,pad_size:w=null}={}){const f=[];w=w??this.pad_size;const P=[w.height,w.width];for(let A=0;Au&&(g[M]=1);$=new n.Tensor("bool",g,$.dims)}f.push($)}return f}generate_crop_boxes(l,d,{crop_n_layers:p=0,overlap_ratio:u=512/1500,points_per_crop:h=32,crop_n_points_downscale_factor:w=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}re(n,"image_processor_class",i.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(l){super(l);const d=this.config.sampling_rate,p=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(d/2),d,null,"kaldi",!0);for(let u=0;up*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:d,transpose:!0})}async _call(l,{padding:d=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:u=!0,return_attention_mask:h=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let w=await this._extract_fbank_features(l,this.config.max_length);if(u){const[g,M]=w.dims,E=w.data;for(let k=0;k0){const B=new Float32Array(M*(g+k));B.set(E),B.fill(this.config.padding_value,E.length);const N=g+k;w=new i.Tensor(w.type,B,[N,M]),h&&(f=new i.Tensor("int64",new BigInt64Array(N),[1,N]),f.data.fill(1n,0,g))}}const[P,A]=w.dims,b=this.config.stride;if(P%b!==0)throw new Error(`The number of frames (${P}) must be a multiple of the stride (${b}).`);const $=w.view(1,Math.floor(P/b),A*b),T={input_features:$};if(h){const g=$.dims[1],M=new BigInt64Array(g);if(f){const E=f.data;for(let k=1,B=0;k{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends i{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>i});var s=t("./src/models/dac/feature_extraction_dac.js");class i extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");class i extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class o extends s.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(o,a,l,d={}){const[p,u,h]=a;return super.pad_image(o,a,{width:u+(l-u%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...d})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l,d=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let u={};if(d){const w=d.length,{input_features:f}=await this.feature_extractor(d,{...p,max_length:w}),P=Math.round(w/this.config.encoder_ds_factor+1e-4),A=1+Math.ceil(P/this.config.stack_factor);u.audio_token_len=[A],u.audio_values=f;const b=this.config.audio_placeholder;if(!l.includes(b))throw new Error(`The input text does not contain the image token ${b}.`);l=l.replaceAll(b,b.repeat(A))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...u}}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor),re(o,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const d=await Promise.all(a.map(h=>this.preprocess(h))),p=await Promise.all(l.map(h=>this.preprocess(h,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,i.stack)(d.map((h,w)=>(0,i.cat)([h.pixel_values,p[w].pixel_values],0)),0),original_sizes:d.map(h=>h.original_size),reshaped_input_sizes:d.map(h=>h.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_pose_estimation(o,a,{threshold:l=null}={}){const d=o.tolist(),[p,u,h,w]=o.dims,f=[];for(let P=0;P{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const d=a.reduce((u,h)=>u+h,0)/a.length,p=a.reduce((u,h)=>u+(h-d)**2,0)/a.length;return a.map(u=>(u-d)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const d=[1,l.length];return{input_values:new i.Tensor("float32",l,d),attention_mask:new i.Tensor("int64",new BigInt64Array(l.length).fill(1n),d)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,d=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;pl*32768),(0,i.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const d=l.mean(1).data,p=l.data,[u,h,w]=l.dims;for(let f=0;f{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>i,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>o});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],i=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function o(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const d=a.match(/^<\|([a-z]{2})\|>$/);if(d&&(a=d[1]),i.has(a))l=a;else{const u=a.length===2?i.keys():i.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(u))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{constructor(l){var d;super(l),(d=this.config).mel_filters??(d.mel_filters=(0,i.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,i.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const d=await(0,i.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=d.data,u=(0,n.max)(p)[0];for(let h=0;hu?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,u)):(p=new Float32Array(u),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>i});var s=t("./src/generation/configuration_utils.js");class i extends s.GenerationConfig{constructor(){super(...arguments);re(this,"return_timestamps",null);re(this,"return_token_timestamps",null);re(this,"num_frames",null);re(this,"alignment_heads",null);re(this,"task",null);re(this,"language",null);re(this,"no_timestamps_token_id",null);re(this,"prompt_ids",null);re(this,"is_multilingual",null);re(this,"lang_to_id",null);re(this,"task_to_id",null);re(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),i=t("./src/utils/tensor.js"),n=t("./src/env.js");const o=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(d,p,u)=>{const h=await(0,s.createInferenceSession)(new Uint8Array(d),p);let w=Promise.resolve();return async f=>{const P=(0,s.isONNXProxy)(),A=Object.fromEntries(Object.entries(f).map(([y,$])=>[y,(P?$.clone():$).ort_tensor])),b=await(w=o?w.then(()=>h.run(A)):h.run(A));return Array.isArray(u)?u.map(y=>new i.Tensor(b[y])):new i.Tensor(b[u])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}re(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>q,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>le,DepthEstimationPipeline:()=>X,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>N,FillMaskPipeline:()=>$,ImageClassificationPipeline:()=>Q,ImageFeatureExtractionPipeline:()=>J,ImageSegmentationPipeline:()=>ie,ImageToImagePipeline:()=>ne,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>we,Pipeline:()=>P,QuestionAnsweringPipeline:()=>y,SummarizationPipeline:()=>g,Text2TextGenerationPipeline:()=>T,TextClassificationPipeline:()=>A,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>G,TokenClassificationPipeline:()=>b,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>V,ZeroShotClassificationPipeline:()=>B,ZeroShotImageClassificationPipeline:()=>ae,ZeroShotObjectDetectionPipeline:()=>R,pipeline:()=>ke});var s=t("./src/tokenizers.js"),i=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var o=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),d=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),u=t("./src/utils/image.js");async function h(Me){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(K=>u.RawImage.read(K)))}async function w(Me,K){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(U=>typeof U=="string"||U instanceof URL?(0,d.read_audio)(U,K):U instanceof Float64Array?new Float32Array(U):U))}function f(Me,K){K&&(Me=Me.map(Ae=>Ae|0));const[U,pe,Pe,Te]=Me;return{xmin:U,ymin:pe,xmax:Pe,ymax:Te}}class P extends o.Callable{constructor({task:K,model:U,tokenizer:pe=null,processor:Pe=null}){super(),this.task=K,this.model=U,this.tokenizer=pe,this.processor=Pe}async dispose(){await this.model.dispose()}}class A extends P{constructor(K){super(K)}async _call(K,{top_k:U=1}={}){const pe=this.tokenizer(K,{padding:!0,truncation:!0}),Pe=await this.model(pe),Te=this.model.config.problem_type==="multi_label_classification"?Le=>Le.sigmoid():Le=>new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),Ae=this.model.config.id2label,Ie=[];for(const Le of Pe.logits){const Ne=Te(Le),Ve=await(0,p.topk)(Ne,U),D=Ve[0].tolist(),z=Ve[1].tolist().map((ee,ce)=>({label:Ae?Ae[ee]:`LABEL_${ee}`,score:D[ce]}));U===1?Ie.push(...z):Ie.push(z)}return Array.isArray(K)||U===1?Ie:Ie[0]}}class b extends P{constructor(K){super(K)}async _call(K,{ignore_labels:U=["O"]}={}){const pe=Array.isArray(K),Pe=this.tokenizer(pe?K:[K],{padding:!0,truncation:!0}),Ae=(await this.model(Pe)).logits,Ie=this.model.config.id2label,Le=[];for(let Ne=0;NeFe==this.tokenizer.sep_token_id);Le[D].map((Fe,je)=>Fe==1&&(je===0||je>z&&Ne.findIndex(Qe=>Qe==Z[je])===-1));const ee=Te[D].tolist(),ce=Ae[D].tolist();for(let Fe=1;Feje==Z[Fe])!==-1)&&(ee[Fe]=-1/0,ce[Fe]=-1/0);const be=(0,l.softmax)(ee).map((Fe,je)=>[Fe,je]),ve=(0,l.softmax)(ce).map((Fe,je)=>[Fe,je]);be[0][0]=0,ve[0][0]=0;const Re=(0,a.product)(be,ve).filter(Fe=>Fe[0][1]<=Fe[1][1]).map(Fe=>[Fe[0][1],Fe[1][1],Fe[0][0]*Fe[1][0]]).sort((Fe,je)=>je[2]-Fe[2]);for(let Fe=0;Feee==this.tokenizer.mask_token_id);if(Ne===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=Pe[Ie][Ne],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),U),Z=D[0].tolist(),z=D[1].tolist();Te.push(z.map((ee,ce)=>{const be=Le.slice();return be[Ne]=ee,{score:Z[ce],token:Number(ee),token_str:this.tokenizer.decode([ee]),sequence:this.tokenizer.decode(be,{skip_special_tokens:!0})}}))}return Array.isArray(K)?Te:Te[0]}}class T extends P{constructor(U){super(U);re(this,"_key","generated_text")}async _call(U,pe={}){Array.isArray(U)||(U=[U]),this.model.config.prefix&&(U=U.map(Ne=>this.model.config.prefix+Ne));const Pe=this.model.config.task_specific_params;Pe&&Pe[this.task]&&Pe[this.task].prefix&&(U=U.map(Ne=>Pe[this.task].prefix+Ne));const Te=this.tokenizer,Ae={padding:!0,truncation:!0};let Ie;this instanceof M&&"_build_translation_inputs"in Te?Ie=Te._build_translation_inputs(U,Ae,pe):Ie=Te(U,Ae);const Le=await this.model.generate({...Ie,...pe});return Te.batch_decode(Le,{skip_special_tokens:!0}).map(Ne=>({[this._key]:Ne}))}}class g extends T{constructor(U){super(U);re(this,"_key","summary_text")}}class M extends T{constructor(U){super(U);re(this,"_key","translation_text")}}function E(Me){return Array.isArray(Me)&&Me.every(K=>"role"in K&&"content"in K)}class k extends P{constructor(K){super(K)}async _call(K,U={}){let pe=!1,Pe=!1,Te;if(typeof K=="string")Te=K=[K];else if(Array.isArray(K)&&K.every(z=>typeof z=="string"))pe=!0,Te=K;else{if(E(K))K=[K];else if(Array.isArray(K)&&K.every(E))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Pe=!0,Te=K.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Ae=U.add_special_tokens??!1,Ie=Pe?!1:U.return_full_text??!0;this.tokenizer.padding_side="left";const Le=this.tokenizer(Te,{add_special_tokens:Ae,padding:!0,truncation:!0}),Ne=await this.model.generate({...Le,...U}),Ve=this.tokenizer.batch_decode(Ne,{skip_special_tokens:!0});let D;!Ie&&Le.input_ids.dims.at(-1)>0&&(D=this.tokenizer.batch_decode(Le.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Z=Array.from({length:K.length},z=>[]);for(let z=0;z[U.toLowerCase(),pe])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(K,U,{hypothesis_template:pe="This example is {}.",multi_label:Pe=!1}={}){const Te=Array.isArray(K);Te||(K=[K]),Array.isArray(U)||(U=[U]);const Ae=U.map(Ne=>pe.replace("{}",Ne)),Ie=Pe||U.length===1,Le=[];for(const Ne of K){const Ve=[];for(const z of Ae){const ee=this.tokenizer(Ne,{text_pair:z,padding:!0,truncation:!0}),ce=await this.model(ee);Ie?Ve.push([ce.logits.data[this.contradiction_id],ce.logits.data[this.entailment_id]]):Ve.push(ce.logits.data[this.entailment_id])}const Z=(Ie?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,ee)=>[z,ee]).sort((z,ee)=>ee[0]-z[0]);Le.push({sequence:Ne,labels:Z.map(z=>U[z[1]]),scores:Z.map(z=>z[0])})}return Te?Le:Le[0]}}class N extends P{constructor(K){super(K)}async _call(K,{pooling:U="none",normalize:pe=!1,quantize:Pe=!1,precision:Te="binary"}={}){const Ae=this.tokenizer(K,{padding:!0,truncation:!0}),Ie=await this.model(Ae);let Le=Ie.last_hidden_state??Ie.logits??Ie.token_embeddings;if(U!=="none")if(U==="mean")Le=(0,p.mean_pooling)(Le,Ae.attention_mask);else if(U==="cls")Le=Le.slice(null,0);else throw Error(`Pooling method '${U}' not supported.`);return pe&&(Le=Le.normalize(2,-1)),Pe&&(Le=(0,p.quantize_embeddings)(Le,Te)),Le}}class J extends P{constructor(K){super(K)}async _call(K,{pool:U=null}={}){const pe=await h(K),{pixel_values:Pe}=await this.processor(pe),Te=await this.model({pixel_values:Pe});let Ae;if(U){if(!("pooler_output"in Te))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ae=Te.pooler_output}else Ae=Te.last_hidden_state??Te.logits??Te.image_embeds;return Ae}}class q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,Pe=await w(K,pe),Te=this.model.config.id2label,Ae=[];for(const Ie of Pe){const Le=await this.processor(Ie),Ve=(await this.model(Le)).logits[0],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),U),Z=D[0].tolist(),ee=D[1].tolist().map((ce,be)=>({label:Te?Te[ce]:`LABEL_${ce}`,score:Z[be]}));Ae.push(ee)}return Array.isArray(K)?Ae:Ae[0]}}class V extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a sound of {}."}={}){const Pe=!Array.isArray(K);Pe&&(K=[K]);const Te=U.map(Ve=>pe.replace("{}",Ve)),Ae=this.tokenizer(Te,{padding:!0,truncation:!0}),Ie=this.processor.feature_extractor.config.sampling_rate,Le=await w(K,Ie),Ne=[];for(const Ve of Le){const D=await this.processor(Ve),Z=await this.model({...Ae,...D}),z=(0,l.softmax)(Z.logits_per_audio.data);Ne.push([...z].map((ee,ce)=>({score:ee,label:U[ce]})))}return Pe?Ne[0]:Ne}}class Y extends P{constructor(K){super(K)}async _call(K,U={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(K,U);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(K,U);case"moonshine":return this._call_moonshine(K,U);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(K,U){U.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),U.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(K);pe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,Te=await w(K,Pe),Ae=[];for(const Ie of Te){const Le=await this.processor(Ie),Ve=(await this.model(Le)).logits[0],D=[];for(const z of Ve)D.push((0,l.max)(z.data)[1]);const Z=this.tokenizer.decode(D);Ae.push({text:Z})}return pe?Ae[0]:Ae}async _call_whisper(K,U){const pe=U.return_timestamps??!1,Pe=U.chunk_length_s??0,Te=U.force_full_sequences??!1;let Ae=U.stride_length_s??null;const Ie={...U};pe==="word"&&(Ie.return_token_timestamps=!0,Ie.return_timestamps=!1);const Le=!Array.isArray(K);Le&&(K=[K]);const Ne=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,D=this.processor.feature_extractor.config.sampling_rate,Z=await w(K,D),z=[];for(const ee of Z){let ce=[];if(Pe>0){if(Ae===null)Ae=Pe/6;else if(Pe<=Ae)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Re=D*Pe,Fe=D*Ae,je=Re-2*Fe;let Qe=0;for(;;){const Xe=Qe+Re,ut=ee.subarray(Qe,Xe),wt=await this.processor(ut),nr=Qe===0,jt=Xe>=ee.length;if(ce.push({stride:[ut.length,nr?0:Fe,jt?0:Fe],input_features:wt.input_features,is_last:jt}),jt)break;Qe+=je}}else ce=[{stride:[ee.length,0,0],input_features:(await this.processor(ee)).input_features,is_last:!0}];for(const Re of ce){Ie.num_frames=Math.floor(Re.stride[0]/Ve);const Fe=await this.model.generate({inputs:Re.input_features,...Ie});pe==="word"?(Re.tokens=Fe.sequences.tolist()[0],Re.token_timestamps=Fe.token_timestamps.tolist()[0].map(je=>(0,l.round)(je,2))):Re.tokens=Fe[0].tolist(),Re.stride=Re.stride.map(je=>je/D)}const[be,ve]=this.tokenizer._decode_asr(ce,{time_precision:Ne,return_timestamps:pe,force_full_sequences:Te});z.push({text:be,...ve})}return Le?z[0]:z}async _call_moonshine(K,U){const pe=!Array.isArray(K);pe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,Te=await w(K,Pe),Ae=[];for(const Ie of Te){const Le=await this.processor(Ie),Ne=Math.floor(Ie.length/Pe)*6,Ve=await this.model.generate({max_new_tokens:Ne,...U,...Le}),D=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Ae.push({text:D})}return pe?Ae[0]:Ae}}class H extends P{constructor(K){super(K)}async _call(K,U={}){const pe=Array.isArray(K),Pe=await h(K),{pixel_values:Te}=await this.processor(Pe),Ae=[];for(const Ie of Te){Ie.dims=[1,...Ie.dims];const Le=await this.model.generate({inputs:Ie,...U}),Ne=this.tokenizer.batch_decode(Le,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Ae.push(Ne)}return pe?Ae:Ae[0]}}class Q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=await h(K),{pixel_values:Pe}=await this.processor(pe),Te=await this.model({pixel_values:Pe}),Ae=this.model.config.id2label,Ie=[];for(const Le of Te.logits){const Ne=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),U),Ve=Ne[0].tolist(),Z=Ne[1].tolist().map((z,ee)=>({label:Ae?Ae[z]:`LABEL_${z}`,score:Ve[ee]}));Ie.push(Z)}return Array.isArray(K)?Ie:Ie[0]}}class ie extends P{constructor(K){super(K),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(K,{threshold:U=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:Pe=.8,label_ids_to_fuse:Te=null,target_sizes:Ae=null,subtask:Ie=null}={}){if(Array.isArray(K)&&K.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Ne=await h(K),Ve=Ne.map(Re=>[Re.height,Re.width]),D=await this.processor(Ne),{inputNames:Z,outputNames:z}=this.model.sessions.model;if(!Z.includes("pixel_values")){if(Z.length!==1)throw Error(`Expected a single input name, but got ${Z.length} inputs: ${Z}.`);const Re=Z[0];if(Re in D)throw Error(`Input name ${Re} already exists in the inputs.`);D[Re]=D.pixel_values}const ee=await this.model(D);let ce=null;if(Ie!==null)ce=this.subtasks_mapping[Ie];else if(this.processor.image_processor){for(const[Re,Fe]of Object.entries(this.subtasks_mapping))if(Fe in this.processor.image_processor){ce=this.processor.image_processor[Fe].bind(this.processor.image_processor),Ie=Re;break}}const be=this.model.config.id2label,ve=[];if(Ie)if(Ie==="panoptic"||Ie==="instance"){const Re=ce(ee,U,pe,Pe,Te,Ae??Ve)[0],Fe=Re.segmentation;for(const je of Re.segments_info){const Qe=new Uint8ClampedArray(Fe.data.length);for(let ut=0;utwt<-1e-5||wt>1+1e-5)&&Xe.sigmoid_();const ut=await u.RawImage.fromTensor(Xe.mul_(255).to("uint8")).resize(Qe[1],Qe[0]);ve.push({label:null,score:null,mask:ut})}}return ve}}class le extends ie{constructor(K){super(K)}async _call(K,U={}){if(Array.isArray(K)&&K.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const Pe=await h(K),Te=await super._call(K,U);return Pe.map((Ie,Le)=>{const Ne=Ie.clone();return Ne.putAlpha(Te[Le].mask),Ne})}}class ae extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a photo of {}"}={}){const Pe=Array.isArray(K),Te=await h(K),Ae=U.map(Z=>pe.replace("{}",Z)),Ie=this.tokenizer(Ae,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Le}=await this.processor(Te),Ne=await this.model({...Ie,pixel_values:Le}),Ve=this.model.config.model_type==="siglip"?Z=>Z.sigmoid().data:Z=>(0,l.softmax)(Z.data),D=[];for(const Z of Ne.logits_per_image){const ee=[...Ve(Z)].map((ce,be)=>({score:ce,label:U[be]}));ee.sort((ce,be)=>be.score-ce.score),D.push(ee)}return Pe?D:D[0]}}class we extends P{constructor(K){super(K)}async _call(K,{threshold:U=.9,percentage:pe=!1}={}){const Pe=Array.isArray(K);if(Pe&&K.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Te=await h(K),Ae=pe?null:Te.map(z=>[z.height,z.width]),{pixel_values:Ie,pixel_mask:Le}=await this.processor(Te),Ne=await this.model({pixel_values:Ie,pixel_mask:Le}),Ve=this.processor.image_processor.post_process_object_detection(Ne,U,Ae),D=this.model.config.id2label,Z=Ve.map(z=>z.boxes.map((ee,ce)=>({score:z.scores[ce],label:D[z.classes[ce]],box:f(ee,!pe)})));return Pe?Z:Z[0]}}class R extends P{constructor(K){super(K)}async _call(K,U,{threshold:pe=.1,top_k:Pe=null,percentage:Te=!1}={}){const Ae=Array.isArray(K),Ie=await h(K),Le=this.tokenizer(U,{padding:!0,truncation:!0}),Ne=await this.processor(Ie),Ve=[];for(let D=0;D({score:ve.scores[Fe],label:ve.labels[Fe],box:f(Re,!Te)}))}else{const ve=this.processor.image_processor.post_process_object_detection(ce,pe,z,!0)[0];be=ve.boxes.map((Re,Fe)=>({score:ve.scores[Fe],label:U[ve.classes[Fe]],box:f(Re,!Te)}))}be.sort((ve,Re)=>Re.score-ve.score),Pe!==null&&(be=be.slice(0,Pe)),Ve.push(be)}return Ae?Ve:Ve[0]}}class O extends P{constructor(K){super(K)}async _call(K,U,pe={}){const Pe=(await h(K))[0],{pixel_values:Te}=await this.processor(Pe),Ae=`${U}`,Ie=this.tokenizer(Ae,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Le=await this.model.generate({inputs:Te,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ie,...pe}),Ve=this.tokenizer.batch_decode(Le)[0].match(/(.*?)<\/s_answer>/);let D=null;return Ve&&Ve.length>=2&&(D=Ve[1].trim()),[{answer:D}]}}class G extends P{constructor(U){super(U);re(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=U.vocoder??null}async _call(U,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(U,{speaker_embeddings:pe}):this._call_text_to_waveform(U)}async _call_text_to_waveform(U){const pe=this.tokenizer(U,{padding:!0,truncation:!0}),{waveform:Pe}=await this.model(pe),Te=this.model.config.sampling_rate;return new d.RawAudio(Pe.data,Te)}async _call_text_to_spectrogram(U,{speaker_embeddings:pe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await i.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof pe=="string"||pe instanceof URL)&&(pe=new Float32Array(await(await fetch(pe)).arrayBuffer())),pe instanceof Float32Array)pe=new p.Tensor("float32",pe,[1,pe.length]);else if(!(pe instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Pe}=this.tokenizer(U,{padding:!0,truncation:!0}),{waveform:Te}=await this.model.generate_speech(Pe,pe,{vocoder:this.vocoder}),Ae=this.processor.feature_extractor.config.sampling_rate;return new d.RawAudio(Te.data,Ae)}}class ne extends P{constructor(K){super(K)}async _call(K){const U=await h(K),pe=await this.processor(U),Pe=await this.model(pe),Te=[];for(const Ae of Pe.reconstruction){const Ie=Ae.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Te.push(u.RawImage.fromTensor(Ie))}return Te.length>1?Te:Te[0]}}class X extends P{constructor(K){super(K)}async _call(K){const U=await h(K),pe=await this.processor(U),{predicted_depth:Pe}=await this.model(pe),Te=[];for(let Ae=0;Ae1?Te:Te[0]}}const ye=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:b,model:i.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:y,model:i.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:$,model:i.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:g,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:T,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:k,model:i.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:B,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:q,model:i.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:V,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[i.AutoModelForSpeechSeq2Seq,i.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:G,model:[i.AutoModelForTextToWaveform,i.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:i.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Q,model:i.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ie,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:le,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:ae,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:we,model:i.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:R,model:i.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:O,model:i.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ne,model:i.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:X,model:i.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:N,model:i.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:J,model:[i.AutoModelForImageFeatureExtraction,i.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),_e=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ke(Me,K=null,{progress_callback:U=null,config:pe=null,cache_dir:Pe=null,local_files_only:Te=!1,revision:Ae="main",device:Ie=null,dtype:Le=null,subfolder:Ne="onnx",use_external_data_format:Ve=null,model_file_name:D=null,session_options:Z={}}={}){Me=_e[Me]??Me;const z=ye[Me.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${Me}. Must be one of [${Object.keys(ye)}]`);K||(K=z.default.model,console.log(`No model specified. Using default model: "${K}".`));const ee={progress_callback:U,config:pe,cache_dir:Pe,local_files_only:Te,revision:Ae,device:Ie,dtype:Le,subfolder:Ne,use_external_data_format:Ve,model_file_name:D,session_options:Z},ce=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),be=await He(ce,K,ee);be.task=Me,(0,a.dispatchCallback)(U,{status:"ready",task:Me,model:K});const ve=z.pipeline;return new ve(be)}async function He(Me,K,U){const pe=Object.create(null),Pe=[];for(const[Te,Ae]of Me.entries()){if(!Ae)continue;let Ie;Array.isArray(Ae)?Ie=new Promise(async(Le,Ne)=>{var D,Z;let Ve;for(const z of Ae){if(z===null){Le(null);return}try{Le(await z.from_pretrained(K,U));return}catch(ee){if((D=ee.message)!=null&&D.includes("Unsupported model type"))Ve=ee;else if((Z=ee.message)!=null&&Z.includes("Could not locate file"))Ve=ee;else{Ne(ee);return}}}Ne(Ve)}):Ie=Ae.from_pretrained(K,U),pe[Te]=Ie,Pe.push(Ie)}await Promise.all(Pe);for(const[Te,Ae]of Object.entries(pe))pe[Te]=await Ae;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ur,AutoTokenizer:()=>Cn,BartTokenizer:()=>hs,BertTokenizer:()=>qr,BlenderbotSmallTokenizer:()=>Jr,BlenderbotTokenizer:()=>Fr,BloomTokenizer:()=>Qr,CLIPTokenizer:()=>Tn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>Xr,CodeLlamaTokenizer:()=>Qs,CohereTokenizer:()=>Pn,ConvBertTokenizer:()=>mr,DebertaTokenizer:()=>Ts,DebertaV2Tokenizer:()=>Es,DistilBertTokenizer:()=>et,ElectraTokenizer:()=>zt,EsmTokenizer:()=>Zs,FalconTokenizer:()=>fs,GPT2Tokenizer:()=>ps,GPTNeoXTokenizer:()=>Ys,GemmaTokenizer:()=>Lr,Grok1Tokenizer:()=>Cs,HerbertTokenizer:()=>Ds,LlamaTokenizer:()=>qs,M2M100Tokenizer:()=>zs,MBart50Tokenizer:()=>ms,MBartTokenizer:()=>Er,MPNetTokenizer:()=>Js,MarianTokenizer:()=>En,MgpstrTokenizer:()=>Ss,MobileBertTokenizer:()=>us,NllbTokenizer:()=>Ls,NougatTokenizer:()=>_r,PreTrainedTokenizer:()=>dt,Qwen2Tokenizer:()=>en,RoFormerTokenizer:()=>Be,RobertaTokenizer:()=>_s,SiglipTokenizer:()=>zr,SpeechT5Tokenizer:()=>cr,SqueezeBertTokenizer:()=>xs,T5Tokenizer:()=>Ir,TokenizerModel:()=>J,VitsTokenizer:()=>Rs,Wav2Vec2CTCTokenizer:()=>Bs,WhisperTokenizer:()=>Ar,XLMRobertaTokenizer:()=>Xs,XLMTokenizer:()=>rr,is_chinese_char:()=>$});var s=t("./src/utils/generic.js"),i=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),d=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function u(ue,F){const j=await Promise.all([(0,n.getModelJSON)(ue,"tokenizer.json",!0,F),(0,n.getModelJSON)(ue,"tokenizer_config.json",!0,F)]);return F.legacy!==null&&(j[1].legacy=F.legacy),j}function h(ue,F){const j=[];let te=0;for(const de of ue.matchAll(F)){const he=de[0];te0&&j.push(he),te=de.index+he.length}return te=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function T(ue,F,j){const te=[];let de=0;for(;dethis.tokens_to_ids.get(j)??this.unk_token_id)}convert_ids_to_tokens(F){return F.map(j=>this.vocab[j]??this.unk_token)}}class q extends J{constructor(F){super(F),this.tokens_to_ids=f(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.max_input_chars_per_word=F.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[j,te]of this.tokens_to_ids)this.vocab[te]=j}encode(F){const j=[];for(const te of F){const de=[...te];if(de.length>this.max_input_chars_per_word){j.push(this.unk_token);continue}let he=!1,Ce=0;const We=[];for(;Ce0&&(Ze=this.config.continuing_subword_prefix+Ze),this.tokens_to_ids.has(Ze)){Ke=Ze;break}--qe}if(Ke===null){he=!0;break}We.push(Ke),Ce=qe}he?j.push(this.unk_token):j.push(...We)}return j}}class V extends J{constructor(F,j){super(F);const te=F.vocab.length;this.vocab=new Array(te),this.scores=new Array(te);for(let de=0;de[de,he])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=j.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,o.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(F){const j=F.chars,te=1;let de=0;for(;de{const ue=[...Array.from({length:94},(de,he)=>he+33),...Array.from({length:12},(de,he)=>he+161),...Array.from({length:82},(de,he)=>he+174)],F=ue.slice();let j=0;for(let de=0;de<256;++de)ue.includes(de)||(ue.push(de),F.push(256+j),j+=1);const te=F.map(de=>String.fromCharCode(de));return Object.fromEntries(ue.map((de,he)=>[de,te[he]]))})(),H=(0,i.reverseDictionary)(Y);class Q extends J{constructor(F){super(F),this.tokens_to_ids=f(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[te,de]of this.tokens_to_ids)this.vocab[de]=te;const j=Array.isArray(F.merges[0]);this.merges=j?F.merges:F.merges.map(te=>te.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((te,de)=>[JSON.stringify(te),de])),this.end_of_word_suffix=F.end_of_word_suffix,this.continuing_subword_suffix=F.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(F){if(F.length===0)return[];const j=this.cache.get(F);if(j!==void 0)return j;const te=Array.from(F);this.end_of_word_suffix&&(te[te.length-1]+=this.end_of_word_suffix);let de=[];if(te.length>1){const he=new l.PriorityQueue((qe,Ke)=>qe.score`<0x${We.toString(16).toUpperCase().padStart(2,"0")}>`);Ce.every(We=>this.tokens_to_ids.has(We))?j.push(...Ce):j.push(this.unk_token)}else j.push(this.unk_token)}return j}}class ie extends J{constructor(F,j){super(F),this.tokens_to_ids=f(j.target_lang?F.vocab[j.target_lang]:F.vocab),this.bos_token=j.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=j.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=j.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=j.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[te,de]of this.tokens_to_ids)this.vocab[de]=te}encode(F){return F}}class le extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"BertNormalizer":return new Me(F);case"Precompiled":return new jt(F);case"Sequence":return new He(F);case"Replace":return new ae(F);case"NFC":return new R(F);case"NFD":return new O(F);case"NFKC":return new G(F);case"NFKD":return new ne(F);case"Strip":return new X(F);case"StripAccents":return new ye(F);case"Lowercase":return new _e(F);case"Prepend":return new ke(F);default:throw new Error(`Unknown Normalizer type: ${F.type}`)}}normalize(F){throw Error("normalize should be implemented in subclass.")}_call(F){return this.normalize(F)}}class ae extends le{normalize(F){const j=w(this.config.pattern);return j===null?F:F.replaceAll(j,this.config.content)}}class we extends le{constructor(){super(...arguments);re(this,"form")}normalize(j){return j=j.normalize(this.form),j}}class R extends we{constructor(){super(...arguments);re(this,"form","NFC")}}class O extends we{constructor(){super(...arguments);re(this,"form","NFD")}}class G extends we{constructor(){super(...arguments);re(this,"form","NFKC")}}class ne extends we{constructor(){super(...arguments);re(this,"form","NFKD")}}class X extends le{normalize(F){return this.config.strip_left&&this.config.strip_right?F=F.trim():(this.config.strip_left&&(F=F.trimStart()),this.config.strip_right&&(F=F.trimEnd())),F}}class ye extends le{normalize(F){return F=b(F),F}}class _e extends le{normalize(F){return F=F.toLowerCase(),F}}class ke extends le{normalize(F){return F=this.config.prepend+F,F}}class He extends le{constructor(F){super(F),this.normalizers=F.normalizers.map(j=>le.fromConfig(j))}normalize(F){return this.normalizers.reduce((j,te)=>te.normalize(j),F)}}class Me extends le{_tokenize_chinese_chars(F){const j=[];for(let te=0;tethis.pre_tokenize_text(te,j)):this.pre_tokenize_text(F,j)).flat()}_call(F,j){return this.pre_tokenize(F,j)}}class U extends K{constructor(F){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text(F,j){return F.trim().match(this.pattern)||[]}}class pe extends K{constructor(F){super(),this.config=F,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text(F,j){return this.add_prefix_space&&!F.startsWith(" ")&&(F=" "+F),(this.use_regex?F.match(this.pattern)||[]:[F]).map(de=>Array.from(this.text_encoder.encode(de),he=>this.byte_encoder[he]).join(""))}}class Pe extends K{constructor(F){super(),this.config=F,this.pattern=w(this.config.pattern,this.config.invert)}pre_tokenize_text(F,j){var te;return this.pattern===null?[]:this.config.invert?F.match(this.pattern)||[]:((te=this.config.behavior)==null?void 0:te.toLowerCase())==="removed"?F.split(this.pattern).filter(de=>de):h(F,this.pattern)}}class Te extends K{constructor(F){super(),this.config=F,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text(F,j){return F.match(this.pattern)||[]}}class Ae extends K{constructor(F){super(),this.config=F;const j=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(j,"gu")}pre_tokenize_text(F,j){return F.match(this.pattern)||[]}}class Ie extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"TemplateProcessing":return new Ve(F);case"ByteLevel":return new D(F);case"RobertaProcessing":return new Ne(F);case"BertProcessing":return new Le(F);case"Sequence":return new Z(F);default:throw new Error(`Unknown PostProcessor type: ${F.type}`)}}post_process(F,...j){throw Error("post_process should be implemented in subclass.")}_call(F,...j){return this.post_process(F,...j)}}class Le extends Ie{constructor(F){super(F),this.cls=F.cls[0],this.sep=F.sep[0]}post_process(F,j=null,{add_special_tokens:te=!0}={}){te&&(F=(0,i.mergeArrays)([this.cls],F,[this.sep]));let de=new Array(F.length).fill(0);if(j!==null){const he=te&&this instanceof Ne?[this.sep]:[],Ce=te?[this.sep]:[];F=(0,i.mergeArrays)(F,he,j,Ce),de=(0,i.mergeArrays)(de,new Array(j.length+he.length+Ce.length).fill(1))}return{tokens:F,token_type_ids:de}}}class Ne extends Le{}class Ve extends Ie{constructor(F){super(F),this.single=F.single,this.pair=F.pair}post_process(F,j=null,{add_special_tokens:te=!0}={}){const de=j===null?this.single:this.pair;let he=[],Ce=[];for(const We of de)"SpecialToken"in We?te&&(he.push(We.SpecialToken.id),Ce.push(We.SpecialToken.type_id)):"Sequence"in We&&(We.Sequence.id==="A"?(he=(0,i.mergeArrays)(he,F),Ce=(0,i.mergeArrays)(Ce,new Array(F.length).fill(We.Sequence.type_id))):We.Sequence.id==="B"&&(he=(0,i.mergeArrays)(he,j),Ce=(0,i.mergeArrays)(Ce,new Array(j.length).fill(We.Sequence.type_id))));return{tokens:he,token_type_ids:Ce}}}class D extends Ie{post_process(F,j=null){return j&&(F=(0,i.mergeArrays)(F,j)),{tokens:F}}}class Z extends Ie{constructor(F){super(F),this.processors=F.processors.map(j=>Ie.fromConfig(j))}post_process(F,j=null,te={}){let de;for(const he of this.processors)if(he instanceof D)F=he.post_process(F).tokens,j&&(j=he.post_process(j).tokens);else{const Ce=he.post_process(F,j,te);F=Ce.tokens,de=Ce.token_type_ids}return{tokens:F,token_type_ids:de}}}class z extends s.Callable{constructor(F){super(),this.config=F,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=F.trim_offsets}static fromConfig(F){if(F===null)return null;switch(F.type){case"WordPiece":return new Re(F);case"Metaspace":return new nr(F);case"ByteLevel":return new Fe(F);case"Replace":return new ee(F);case"ByteFallback":return new ce(F);case"Fuse":return new be(F);case"Strip":return new ve(F);case"Sequence":return new Qe(F);case"CTC":return new je(F);case"BPEDecoder":return new Xe(F);default:throw new Error(`Unknown Decoder type: ${F.type}`)}}_call(F){return this.decode(F)}decode(F){return this.decode_chain(F).join("")}decode_chain(F){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends z{decode_chain(F){const j=w(this.config.pattern);return j===null?F:F.map(te=>te.replaceAll(j,this.config.content))}}class ce extends z{constructor(F){super(F),this.text_decoder=new TextDecoder}decode_chain(F){const j=[];let te=[];for(const de of F){let he=null;if(de.length===6&&de.startsWith("<0x")&&de.endsWith(">")){const Ce=parseInt(de.slice(3,5),16);isNaN(Ce)||(he=Ce)}if(he!==null)te.push(he);else{if(te.length>0){const Ce=this.text_decoder.decode(Uint8Array.from(te));j.push(Ce),te=[]}j.push(de)}}if(te.length>0){const de=this.text_decoder.decode(Uint8Array.from(te));j.push(de),te=[]}return j}}class be extends z{decode_chain(F){return[F.join("")]}}class ve extends z{constructor(F){super(F),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(F){return F.map(j=>{let te=0;for(let he=0;he(te!==0&&(j.startsWith(this.config.prefix)?j=j.replace(this.config.prefix,""):j=" "+j),this.cleanup&&(j=A(j)),j))}}class Fe extends z{constructor(F){super(F),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(F){const j=F.join(""),te=new Uint8Array([...j].map(he=>this.byte_decoder[he]));return this.text_decoder.decode(te)}decode_chain(F){const j=[];let te=[];for(const de of F)this.added_tokens.find(he=>he.content===de)!==void 0?(te.length>0&&(j.push(this.convert_tokens_to_string(te)),te=[]),j.push(de)):te.push(de);return te.length>0&&j.push(this.convert_tokens_to_string(te)),j}}class je extends z{constructor(F){super(F),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(F){if(F.length===0)return"";const j=[F[0]];for(let he=1;hehe!==this.pad_token).join("");return this.cleanup&&(de=A(de).replaceAll(this.word_delimiter_token," ").trim()),de}decode_chain(F){return[this.convert_tokens_to_string(F)]}}class Qe extends z{constructor(F){super(F),this.decoders=F.decoders.map(j=>z.fromConfig(j))}decode_chain(F){return this.decoders.reduce((j,te)=>te.decode_chain(j),F)}}class Xe extends z{constructor(F){super(F),this.suffix=this.config.suffix}decode_chain(F){return F.map((j,te)=>j.replaceAll(this.suffix,te===F.length-1?"":" "))}}class ut extends z{decode_chain(F){let j="";for(let te=1;tete.normalize("NFKC")).join("~"):F=F.normalize("NFKC"),F}}class dr extends K{constructor(F){super(),this.tokenizers=F.pretokenizers.map(j=>K.fromConfig(j))}pre_tokenize_text(F,j){return this.tokenizers.reduce((te,de)=>de.pre_tokenize(te,j),[F])}}class ds extends K{constructor(F){super()}pre_tokenize_text(F,j){return F.match(/\w+|[^\w\s]+/g)||[]}}class Fs extends K{constructor(F){super()}pre_tokenize_text(F,j){return g(F)}}class Dr extends K{constructor(F){super(),this.config=F,this.pattern=w(this.config.pattern),this.content=this.config.content}pre_tokenize_text(F,j){return this.pattern===null?[F]:[F.replaceAll(this.pattern,this.config.content)]}}const cs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Os(ue,F,j,te){for(const de of Object.keys(ue)){const he=F-ue[de].length,Ce=j(de),We=new Array(he).fill(Ce);ue[de]=te==="right"?(0,i.mergeArrays)(ue[de],We):(0,i.mergeArrays)(We,ue[de])}}function jr(ue,F){for(const j of Object.keys(ue))ue[j].length=F}class dt extends s.Callable{constructor(j,te){super();re(this,"return_token_type_ids",!1);re(this,"padding_side","right");this._tokenizer_config=te,this.normalizer=le.fromConfig(j.normalizer),this.pre_tokenizer=K.fromConfig(j.pre_tokenizer),this.model=J.fromConfig(j.model,te),this.post_processor=Ie.fromConfig(j.post_processor),this.decoder=z.fromConfig(j.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const de of j.added_tokens){const he=new N(de);this.added_tokens.push(he),this.model.tokens_to_ids.set(he.content,he.id),this.model.vocab[he.id]=he.content,he.special&&(this.special_tokens.push(he.content),this.all_special_ids.push(he.id))}if(this.additional_special_tokens=te.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((de,he)=>he.content.length-de.content.length).map(de=>`${de.lstrip?"\\s*":""}(${(0,i.escapeRegExp)(de.content)})${de.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=te.model_max_length,this.remove_space=te.remove_space,this.clean_up_tokenization_spaces=te.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=te.do_lowercase_and_remove_accent??!1,te.padding_side&&(this.padding_side=te.padding_side),this.legacy=!1,this.chat_template=te.chat_template??null,Array.isArray(this.chat_template)){const de=Object.create(null);for(const{name:he,template:Ce}of this.chat_template){if(typeof he!="string"||typeof Ce!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');de[he]=Ce}this.chat_template=de}this._compiled_template_cache=new Map}getToken(...j){for(const te of j){const de=this._tokenizer_config[te];if(de)if(typeof de=="object"){if(de.__type==="AddedToken")return de.content;throw Error(`Unknown token: ${de}`)}else return de}return null}static async from_pretrained(j,{progress_callback:te=null,config:de=null,cache_dir:he=null,local_files_only:Ce=!1,revision:We="main",legacy:qe=null}={}){const Ke=await u(j,{progress_callback:te,config:de,cache_dir:he,local_files_only:Ce,revision:We,legacy:qe});return new this(...Ke)}_call(j,{text_pair:te=null,add_special_tokens:de=!0,padding:he=!1,truncation:Ce=null,max_length:We=null,return_tensor:qe=!0,return_token_type_ids:Ke=null}={}){const Ze=Array.isArray(j);let ht;if(Ze){if(j.length===0)throw Error("text array must be non-empty");if(te!==null){if(Array.isArray(te)){if(j.length!==te.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");ht=j.map((kt,Wt)=>this._encode_plus(kt,{text_pair:te[Wt],add_special_tokens:de,return_token_type_ids:Ke}))}else ht=j.map(kt=>this._encode_plus(kt,{add_special_tokens:de,return_token_type_ids:Ke}))}else{if(j==null)throw Error("text may not be null or undefined");if(Array.isArray(te))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");ht=[this._encode_plus(j,{text_pair:te,add_special_tokens:de,return_token_type_ids:Ke})]}if(We===null?he==="max_length"?We=this.model_max_length:We=(0,o.max)(ht.map(kt=>kt.input_ids.length))[0]:Ce||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),We=Math.min(We,this.model_max_length??1/0),he||Ce)for(let kt=0;ktWe?Ce&&jr(ht[kt],We):he&&Os(ht[kt],We,Wt=>Wt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ct={};if(qe){if(!(he&&Ce)&&ht.some(Wt=>{var Ot;for(const Ut of Object.keys(Wt))if(Wt[Ut].length!==((Ot=ht[0][Ut])==null?void 0:Ot.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const kt=[ht.length,ht[0].input_ids.length];for(const Wt of Object.keys(ht[0]))Ct[Wt]=new a.Tensor("int64",BigInt64Array.from(ht.flatMap(Ot=>Ot[Wt]).map(BigInt)),kt)}else{for(const kt of Object.keys(ht[0]))Ct[kt]=ht.map(Wt=>Wt[kt]);if(!Ze)for(const kt of Object.keys(Ct))Ct[kt]=Ct[kt][0]}return Ct}_encode_text(j){return j===null?null:(this.added_tokens_regex?j.split(this.added_tokens_regex).filter(he=>he):[j]).map((he,Ce)=>{if(this.added_tokens.find(qe=>qe.content===he)!==void 0)return he;{if(this.remove_space===!0&&(he=he.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(he=y(he)),this.normalizer!==null&&(he=this.normalizer(he)),he.length===0)return[];const qe=this.pre_tokenizer!==null?this.pre_tokenizer(he,{section_index:Ce}):[he];return this.model(qe)}}).flat()}_encode_plus(j,{text_pair:te=null,add_special_tokens:de=!0,return_token_type_ids:he=null}={}){const{tokens:Ce,token_type_ids:We}=this._tokenize_helper(j,{pair:te,add_special_tokens:de}),qe=this.model.convert_tokens_to_ids(Ce),Ke={input_ids:qe,attention_mask:new Array(qe.length).fill(1)};return(he??this.return_token_type_ids)&&We&&(Ke.token_type_ids=We),Ke}_tokenize_helper(j,{pair:te=null,add_special_tokens:de=!1}={}){const he=this._encode_text(j),Ce=this._encode_text(te);return this.post_processor?this.post_processor(he,Ce,{add_special_tokens:de}):{tokens:(0,i.mergeArrays)(he??[],Ce??[])}}tokenize(j,{pair:te=null,add_special_tokens:de=!1}={}){return this._tokenize_helper(j,{pair:te,add_special_tokens:de}).tokens}encode(j,{text_pair:te=null,add_special_tokens:de=!0,return_token_type_ids:he=null}={}){return this._encode_plus(j,{text_pair:te,add_special_tokens:de,return_token_type_ids:he}).input_ids}batch_decode(j,te={}){return j instanceof a.Tensor&&(j=j.tolist()),j.map(de=>this.decode(de,te))}decode(j,te={}){if(j instanceof a.Tensor&&(j=P(j)),!Array.isArray(j)||j.length===0||!(0,i.isIntegralNumber)(j[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(j,te)}decode_single(j,{skip_special_tokens:te=!1,clean_up_tokenization_spaces:de=null}){let he=this.model.convert_ids_to_tokens(j);te&&(he=he.filter(We=>!this.special_tokens.includes(We)));let Ce=this.decoder?this.decoder(he):he.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ce=Ce.replaceAll(this.decoder.end_of_word_suffix," "),te&&(Ce=Ce.trim())),(de??this.clean_up_tokenization_spaces)&&(Ce=A(Ce)),Ce}get_chat_template({chat_template:j=null,tools:te=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const de=this.chat_template;if(j!==null&&Object.hasOwn(de,j))j=de[j];else if(j===null)if(te!==null&&"tool_use"in de)j=de.tool_use;else if("default"in de)j=de.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(de).sort()}.`)}else if(j===null)if(this.chat_template)j=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return j}apply_chat_template(j,{tools:te=null,documents:de=null,chat_template:he=null,add_generation_prompt:Ce=!1,tokenize:We=!0,padding:qe=!1,truncation:Ke=!1,max_length:Ze=null,return_tensor:ht=!0,return_dict:Ct=!1,tokenizer_kwargs:kt={},...Wt}={}){if(he=this.get_chat_template({chat_template:he,tools:te}),typeof he!="string")throw Error(`chat_template must be a string, but got ${typeof he}`);let Ot=this._compiled_template_cache.get(he);Ot===void 0&&(Ot=new d.Template(he),this._compiled_template_cache.set(he,Ot));const Ut=Object.create(null);for(const fr of cs){const Yr=this.getToken(fr);Yr&&(Ut[fr]=Yr)}const vr=Ot.render({messages:j,add_generation_prompt:Ce,tools:te,documents:de,...Ut,...Wt});if(We){const fr=this._call(vr,{add_special_tokens:!1,padding:qe,truncation:Ke,max_length:Ze,return_tensor:ht,...kt});return Ct?fr:fr.input_ids}return vr}}class qr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ur extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class us extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class xs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ts extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Es extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ds extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class mr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Be extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class et extends dt{}class it extends dt{}class rr extends dt{constructor(j,te){super(j,te);re(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class zt extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ir extends dt{}class ps extends dt{}class hs extends dt{}class Er extends dt{constructor(F,j){super(F,j),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)),this.lang_to_token=te=>te}_build_translation_inputs(F,j,te){return br(this,F,j,te)}}class ms extends Er{}class _s extends dt{}class Qr extends dt{}const Ps="▁";class qs extends dt{constructor(j,te){super(j,te);re(this,"padding_side","left");this.legacy=te.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new wt({replacement:Ps,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(j){if(j===null)return null;if(this.legacy||j.length===0)return super._encode_text(j);let te=super._encode_text(Ps+j.replaceAll(Ps," "));return te.length>1&&te[0]===Ps&&this.special_tokens.includes(te[1])&&(te=te.slice(1)),te}}class Qs extends dt{}class Xs extends dt{}class Js extends dt{}class fs extends dt{}class Ys extends dt{}class Zs extends dt{}class en extends dt{}class Lr extends dt{}class Cs extends dt{}function br(ue,F,j,te){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const de=te.src_lang,he=te.tgt_lang;if(!ue.language_codes.includes(he))throw new Error(`Target language code "${he}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(de!==void 0){if(!ue.language_codes.includes(de))throw new Error(`Source language code "${de}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const Ce of ue.post_processor.config.single)if("SpecialToken"in Ce&&ue.languageRegex.test(Ce.SpecialToken.id)){Ce.SpecialToken.id=ue.lang_to_token(de);break}}return te.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(he)])[0],ue._call(F,j)}class Ls extends dt{constructor(F,j){super(F,j),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)),this.lang_to_token=te=>te}_build_translation_inputs(F,j,te){return br(this,F,j,te)}}class zs extends dt{constructor(F,j){super(F,j),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)).map(te=>te.slice(2,-2)),this.lang_to_token=te=>`__${te}__`}_build_translation_inputs(F,j,te){return br(this,F,j,te)}}class Ar extends dt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(F,{return_timestamps:j=!1,return_language:te=!1,time_precision:de=null,force_full_sequences:he=!0}={}){if(de===null)throw Error("Must specify time_precision");let Ce=null;const We=j==="word";function qe(){return{language:Ce,timestamp:[null,null],text:""}}const Ke=[];let Ze=qe(),ht=0;const Ct=this.timestamp_begin,Wt=Ct+1500;let Ot=[],Ut=[],vr=!1,fr=null;const Yr=new Set(this.all_special_ids);for(const Gt of F){const Zt=Gt.tokens,gr=We?Gt.token_timestamps:null;let Zr=null,ws=Ct;if("stride"in Gt){const[Rt,Jt,qt]=Gt.stride;if(ht-=Jt,fr=Rt-qt,Jt&&(ws=Jt/de+Ct),qt)for(let er=Zt.length-1;er>=0;--er){const ir=Number(Zt[er]);if(ir>=Ct){if(Zr!==null&&(ir-Ct)*de=Ct&&Jt<=Wt){const qt=(Jt-Ct)*de+ht,er=(0,o.round)(qt,2);if(Zr!==null&&Jt>=Zr)vr=!0;else if(vr||Ot.length>0&&Jt0?(Ot.push(Ht),We&&Ut.push(ur)):Ot.every(Rt=>Rt.length===0)&&(Ze=qe(),Ot=[],Ht=[],Ut=[],ur=[])}if(Ot.length>0){if(he&&j)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Gt,Zt]=this.findLongestCommonSequence(Ot,Ut),gr=this.decode(Gt);Ze.text=gr,We&&(Ze.words=this.collateWordTimestamps(Gt,Zt,Ce)),Ke.push(Ze)}let xr=Object.create(null);const gs=Ke.map(Gt=>Gt.text).join("");if(j||te){for(let Gt=0;Gt0;let We=Ce?[]:null,qe=Ce?j[0]:null;for(let Ke=1;KeJt===ws[qt]&&qe[gs+qt]<=j[Ke][gr+qt]).length:Ht=Zt.filter((Jt,qt)=>Jt===ws[qt]).length;const ur=xr/1e4,Rt=Ht/xr+ur;Ht>1&&Rt>ht&&(ht=Rt,Ct=[gs,Gt,gr,Zr])}const[Wt,Ot,Ut,vr]=Ct,fr=Math.floor((Ot+Wt)/2),Yr=Math.floor((vr+Ut)/2);he.push(...te.slice(0,fr)),te=Ze.slice(Yr),de=te.length,Ce&&(We.push(...qe.slice(0,fr)),qe=j[Ke].slice(Yr))}return he.push(...te),Ce?(We.push(...qe),[he,We]):[he,[]]}collateWordTimestamps(F,j,te){const[de,he,Ce]=this.combineTokensIntoWords(F,te),We=[];for(let qe=0;qe=de){const We=((Ce-de)*te).toFixed(2);he.push(`<|${We}|>`),he.push([])}else he[he.length-1].push(Ce);return he=he.map(Ce=>typeof Ce=="string"?Ce:super.decode(Ce,j)),he.join("")}splitTokensOnUnicode(F){const j=this.decode(F,{decode_with_timestamps:!0}),te="�",de=[],he=[],Ce=[];let We=[],qe=[],Ke=0;for(let Ze=0;Ze=this.model.tokens_to_ids.get("<|endoftext|>"),Wt=Ze.startsWith(" "),Ot=Ze.trim(),Ut=qe.test(Ot);if(kt||Wt||Ut||he.length===0)he.push(Ze),Ce.push(ht),We.push(Ct);else{const vr=he.length-1;he[vr]+=Ze,Ce[vr].push(...ht),We[vr].push(...Ct)}}return[he,Ce,We]}mergePunctuations(F,j,te,de,he){const Ce=structuredClone(F),We=structuredClone(j),qe=structuredClone(te);let Ke=Ce.length-2,Ze=Ce.length-1;for(;Ke>=0;)Ce[Ke].startsWith(" ")&&de.includes(Ce[Ke].trim())?(Ce[Ze]=Ce[Ke]+Ce[Ze],We[Ze]=(0,i.mergeArrays)(We[Ke],We[Ze]),qe[Ze]=(0,i.mergeArrays)(qe[Ke],qe[Ze]),Ce[Ke]="",We[Ke]=[],qe[Ke]=[]):Ze=Ke,--Ke;for(Ke=0,Ze=1;Zeht),We.filter(ht=>ht.length>0),qe.filter(ht=>ht.length>0)]}}class Xr extends dt{}class Tn extends dt{}class zr extends dt{}class En extends dt{constructor(F,j){super(F,j),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(te=>this.languageRegex.test(te)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(F){if(F===null)return null;const[j,...te]=F.trim().split(this.languageRegex);if(te.length===0)return super._encode_text(j);if(te.length===2){const[de,he]=te;return this.supported_language_codes.includes(de)||console.warn(`Unsupported language code "${de}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,i.mergeArrays)([de],super._encode_text(he))}}}class Bs extends dt{}class Fr extends dt{}class Jr extends dt{}class cr extends dt{}class _r extends dt{}class Rs extends dt{constructor(F,j){super(F,j),this.decoder=new ut({})}}class Pn extends dt{}class Ss extends dt{}class Cn{static async from_pretrained(F,{progress_callback:j=null,config:te=null,cache_dir:de=null,local_files_only:he=!1,revision:Ce="main",legacy:We=null}={}){var Ct;const[qe,Ke]=await u(F,{progress_callback:j,config:te,cache_dir:de,local_files_only:he,revision:Ce,legacy:We}),Ze=((Ct=Ke.tokenizer_class)==null?void 0:Ct.replace(/Fast$/,""))??"PreTrainedTokenizer";let ht=this.TOKENIZER_CLASS_MAPPING[Ze];return ht||(console.warn(`Unknown tokenizer class "${Ze}", attempting to construct from base class.`),ht=dt),new ht(qe,Ke)}}re(Cn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Ir,DistilBertTokenizer:et,CamembertTokenizer:it,DebertaTokenizer:Ts,DebertaV2Tokenizer:Es,BertTokenizer:qr,HerbertTokenizer:Ds,ConvBertTokenizer:mr,RoFormerTokenizer:Be,XLMTokenizer:rr,ElectraTokenizer:zt,MobileBertTokenizer:us,SqueezeBertTokenizer:xs,AlbertTokenizer:Ur,GPT2Tokenizer:ps,BartTokenizer:hs,MBartTokenizer:Er,MBart50Tokenizer:ms,RobertaTokenizer:_s,WhisperTokenizer:Ar,CodeGenTokenizer:Xr,CLIPTokenizer:Tn,SiglipTokenizer:zr,MarianTokenizer:En,BloomTokenizer:Qr,NllbTokenizer:Ls,M2M100Tokenizer:zs,LlamaTokenizer:qs,CodeLlamaTokenizer:Qs,XLMRobertaTokenizer:Xs,MPNetTokenizer:Js,FalconTokenizer:fs,GPTNeoXTokenizer:Ys,EsmTokenizer:Zs,Wav2Vec2CTCTokenizer:Bs,BlenderbotTokenizer:Fr,BlenderbotSmallTokenizer:Jr,SpeechT5Tokenizer:cr,NougatTokenizer:_r,VitsTokenizer:Rs,Qwen2Tokenizer:en,GemmaTokenizer:Lr,Grok1Tokenizer:Cs,CohereTokenizer:Pn,MgpstrTokenizer:Ss,PreTrainedTokenizer:dt})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>h,hanning:()=>u,mel_filter_bank:()=>$,read_audio:()=>d,spectrogram:()=>k,window_function:()=>B});var s=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),o=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function d(V,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(V)).arrayBuffer(),Q=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${Q.sampleRate}Hz.`);const ie=await Q.decodeAudioData(H);let le;if(ie.numberOfChannels===2){const ae=Math.sqrt(2),we=ie.getChannelData(0),R=ie.getChannelData(1);le=new Float32Array(we.length);for(let O=0;O2595*Math.log10(1+V/700),kaldi:V=>1127*Math.log(1+V/700),slaney:(V,Y=1e3,H=15,Q=27/Math.log(6.4))=>V>=Y?H+Math.log(V/Y)*Q:3*V/200};function f(V,Y="htk"){const H=w[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?H(V):V.map(Q=>H(Q))}const P={htk:V=>700*(10**(V/2595)-1),kaldi:V=>700*(Math.exp(V/1127)-1),slaney:(V,Y=1e3,H=15,Q=Math.log(6.4)/27)=>V>=H?Y*Math.exp(Q*(V-H)):200*V/3};function A(V,Y="htk"){const H=P[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?H(V):V.map(Q=>H(Q))}function b(V,Y){const H=Float64Array.from({length:Y.length-1},(ae,we)=>Y[we+1]-Y[we]),Q=Array.from({length:V.length},()=>new Array(Y.length));for(let ae=0;aenew Array(V.length));for(let ae=0;aeV+Q*le)}function $(V,Y,H,Q,ie,le=null,ae="htk",we=!1){if(le!==null&&le!=="slaney")throw new Error('norm must be one of null or "slaney"');const R=f(H,ae),O=f(Q,ae),G=y(R,O,Y+2);let ne=A(G,ae),X;if(we){const _e=ie/(V*2);X=f(Float64Array.from({length:V},(ke,He)=>He*_e),ae),ne=G}else X=y(0,Math.floor(ie/2),V);const ye=b(X,ne);if(le!==null&&le==="slaney")for(let _e=0;_eie)throw Error(`frame_length (${H}) may not be larger than fft_length (${ie})`);if(Pe!==H)throw new Error(`Length of the window (${Pe}) must equal frame_length (${H})`);if(Q<=0)throw new Error("hop_length must be greater than zero");if(le===null&&G!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(ae){if(we!=="reflect")throw new Error(`pad_mode="${we}" not implemented yet.`);const be=Math.floor((ie-1)/2)+1;V=T(V,be,be)}let Te=Math.floor(1+Math.floor((V.length-H)/Q));Me!==null&&TeTe?U&&(Le=K):Le=Ie=K);const Ne=new i.FFT(ie),Ve=new Float64Array(ie),D=new Float64Array(Ne.outputBufferSize),Z=new Float32Array(Ae*Le);for(let be=0;be=1;--Fe)Ve[Fe]-=O*Ve[Fe-1];Ve[0]*=1-O}for(let Fe=0;FeMath.pow(we,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(H&&(ae=ae.subarray(0,V)),Q===null)return ae;if(V>Q)throw new Error(`Length of the window (${V}) may not be larger than frame_length (${Q})`);return ae}function N(V,Y){let H=44;const Q=new ArrayBuffer(H+V.length*4),ie=new DataView(Q);J(ie,0,"RIFF"),ie.setUint32(4,36+V.length*4,!0),J(ie,8,"WAVE"),J(ie,12,"fmt "),ie.setUint32(16,16,!0),ie.setUint16(20,3,!0),ie.setUint16(22,1,!0),ie.setUint32(24,Y,!0),ie.setUint32(28,Y*4,!0),ie.setUint16(32,4,!0),ie.setUint16(34,32,!0),J(ie,36,"data"),ie.setUint32(40,V.length*4,!0);for(let le=0;le{let le=await ie.arrayBuffer();a.writeFileSync(Q,Buffer.from(le))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Y,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>i,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>d,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>o,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",i="config.json",n="preprocessor_config.json",o=n,a="processor_config.json",l="chat_template.json",d="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>d,calculateReflectOffset:()=>w,count:()=>b,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>o,len:()=>A,mergeArrays:()=>u,pick:()=>P,pop:()=>p,product:()=>h,reverseDictionary:()=>i,saveBlob:()=>f});function s(y,$){y&&y($)}function i(y){return Object.fromEntries(Object.entries(y).map(([$,T])=>[T,$]))}function n(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function o(y){var $,T,g;return((g=(T=($=y==null?void 0:y.prototype)==null?void 0:$.__proto__)==null?void 0:T.constructor)==null?void 0:g.name)==="TypedArray"}function a(y){return Number.isInteger(y)||typeof y=="bigint"}function l(y){return y==null||y===-1}function d(y){const $=[];let T=y;for(;Array.isArray(T);)$.push(T.length),T=T[0];return $}function p(y,$,T=void 0){const g=y[$];if(g!==void 0)return delete y[$],g;if(T===void 0)throw Error(`Key ${$} does not exist in object.`);return T}function u(...y){return Array.prototype.concat.apply([],y)}function h(...y){return y.reduce(($,T)=>$.flatMap(g=>T.map(M=>[g,M])))}function w(y,$){return Math.abs((y+$)%(2*$)-$)}function f(y,$){const T=URL.createObjectURL($),g=document.createElement("a");g.href=T,g.download=y,g.click(),g.remove(),URL.revokeObjectURL(T)}function P(y,$){return Object.assign({},...$.map(T=>{if(y[T]!==void 0)return{[T]:y[T]}}))}function A(y){let $=0;for(const T of y)++$;return $}function b(y,$){let T=0;for(const g of y)g===$&&++T;return T}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>i,PriorityQueue:()=>s,TokenLattice:()=>o});class s{constructor(d=(u,h)=>u>h,p=1/0){this._heap=[],this._comparator=d,this._maxSize=p}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const p of d)if(this.size0&&this._swap(0,p),this._heap.pop(),this._siftDown(),d}replace(d){const p=this.peek();return this._heap[0]=d,this._siftDown(),p}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,p){return this._comparator(this._heap[d],this._heap[p])}_swap(d,p){const u=this._heap[d];this._heap[d]=this._heap[p],this._heap[p]=u}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const h=new a(this.bosTokenId,0,0,0,0),w=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(h.clone()),this.nodes.push(w.clone()),this.beginNodes[this.len].push(w),this.endNodes[0].push(h)}insert(d,p,u,h){const w=this.nodes.length,f=new a(h,w,d,p,u);this.beginNodes[d].push(f),this.endNodes[d+p].push(f),this.nodes.push(f)}viterbi(){const d=this.len;let p=0;for(;p<=d;){if(this.beginNodes[p].length==0)return[];for(let P of this.beginNodes[p]){P.prev=null;let A=0,b=null;for(let y of this.endNodes[p]){const $=y.backtraceScore+P.score;(b===null||$>A)&&(b=y.clone(),A=$)}if(b!==null)P.prev=b,P.backtraceScore=A;else return[]}++p}const u=[],w=this.beginNodes[d][0].prev;if(w===null)return[];let f=w.clone();for(;f.prev!==null;)u.push(f.clone()),f=f.clone().prev.clone();return u.reverse(),u}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(p=>this.piece(p))}tokenIds(){return this.viterbi().map(p=>p.tokenId)}}class a{constructor(d,p,u,h,w){this.tokenId=d,this.nodeId=p,this.pos=u,this.length=h,this.score=w,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>o,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),i=t("./src/utils/devices.js");const n=function(){let d;return async function(){if(d===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)d=!1;else try{d=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{d=!1}return d}}(),o=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[i.DEVICE_TYPES.wasm]:o.q8}),l=Object.freeze({[o.fp32]:"",[o.fp16]:"_fp16",[o.int8]:"_int8",[o.uint8]:"_uint8",[o.q8]:"_quantized",[o.q4]:"_q4",[o.q4f16]:"_q4f16",[o.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let i=function(...n){return i._call(...n)};return Object.setPrototypeOf(i,new.target.prototype)}_call(...i){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>u,getModelFile:()=>A,getModelJSON:()=>b});var s=t("?7a2c"),i=t("?a42a"),n=t("./src/env.js"),o=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class d{constructor(g){if(this.filePath=g,this.headers=new Headers,this.exists=s.existsSync(g),this.exists){this.status=200,this.statusText="OK";let M=s.statSync(g);this.headers.set("content-length",M.size.toString()),this.updateContentType();const E=s.createReadStream(g);this.body=new ReadableStream({start(k){E.on("data",B=>k.enqueue(B)),E.on("end",()=>k.close()),E.on("error",B=>k.error(B))},cancel(){E.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const g=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[g]??"application/octet-stream")}clone(){let g=new d(this.filePath);return g.exists=this.exists,g.status=this.status,g.statusText=this.statusText,g.headers=new Headers(this.headers),g}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const g=await s.promises.readFile(this.filePath);return new Blob([g],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(T,g=null,M=null){let E;try{E=new URL(T)}catch{return!1}return!(g&&!g.includes(E.protocol)||M&&!M.includes(E.hostname))}async function u(T){var g;if(n.env.useFS&&!p(T,["http:","https:","blob:"]))return new d(T.toString());if(typeof process<"u"&&((g=process==null?void 0:process.release)==null?void 0:g.name)==="node"){const M=!!(As!=null&&As.TESTING_REMOTELY),E=n.env.version,k=new Headers;if(k.set("User-Agent",`transformers.js/${E}; is_ci/${M};`),p(T,["http:","https:"],["huggingface.co","hf.co"])){const N=(As==null?void 0:As.HF_TOKEN)??(As==null?void 0:As.HF_ACCESS_TOKEN);N&&k.set("Authorization",`Bearer ${N}`)}return fetch(T,{headers:k})}else return fetch(T)}const h={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function w(T,g,M){if(!M)return null;const E=h[T]??`Error (${T}) occurred while trying to load file`;throw Error(`${E}: "${g}".`)}class f{constructor(g){this.path=g}async match(g){let M=i.join(this.path,g),E=new d(M);if(E.exists)return E}async put(g,M,E=void 0){let k=i.join(this.path,g);try{const B=M.headers.get("Content-Length"),N=parseInt(B??"0");let J=0;await s.promises.mkdir(i.dirname(k),{recursive:!0});const q=s.createWriteStream(k),V=M.body.getReader();for(;;){const{done:Y,value:H}=await V.read();if(Y)break;await new Promise((ie,le)=>{q.write(H,ae=>{if(ae){le(ae);return}ie()})}),J+=H.length;const Q=N?J/N*100:0;E==null||E({progress:Q,loaded:J,total:N})}q.close()}catch(B){try{await s.promises.unlink(k)}catch{}throw B}}}async function P(T,...g){for(let M of g)try{let E=await T.match(M);if(E)return E}catch{continue}}async function A(T,g,M=!0,E={},k=!1){if(!n.env.allowLocalModels){if(E.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,o.dispatchCallback)(E.progress_callback,{status:"initiate",name:T,file:g});let B;if(!B&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{B=await caches.open("transformers-cache")}catch(G){console.warn("An error occurred while opening the browser cache:",G)}}if(!B&&n.env.useFSCache&&(B=new f(E.cache_dir??n.env.cacheDir)),!B&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");B=n.env.customCache}const N=E.revision??"main";let J=$(T,g),q=$(n.env.localModelPath,J),V=J,Y=$(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",T).replaceAll("{revision}",encodeURIComponent(N)),g),H=N==="main"?J:$(T,N,g),Q,ie=B instanceof f?H:Y,le=!1,ae;B&&(ae=await P(B,q,ie));const we=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(J,["http:","https:"])){if(E.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${V}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${V}.`)}else try{ae=await u(V),Q=V}catch(ne){console.warn(`Unable to load from local path "${V}": "${ne}"`)}if(ae===void 0||ae.status===404){if(E.local_files_only||!n.env.allowRemoteModels){if(M)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${V}".`);return null}if(ae=await u(Y),ae.status!==200)return w(ae.status,Y,M);Q=ie}le=B&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,o.dispatchCallback)(E.progress_callback,{status:"download",name:T,file:g});let R;if(!(n.apis.IS_NODE_ENV&&k)){let G;E.progress_callback?we&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(G=new Uint8Array(await ae.arrayBuffer()),(0,o.dispatchCallback)(E.progress_callback,{status:"progress",name:T,file:g,progress:100,loaded:G.length,total:G.length})):G=await y(ae,ne=>{(0,o.dispatchCallback)(E.progress_callback,{status:"progress",name:T,file:g,...ne})}):G=new Uint8Array(await ae.arrayBuffer()),R=G}if(le&&Q&&await B.match(Q)===void 0&&(R?await B.put(Q,new Response(R,{headers:ae.headers})).catch(G=>{console.warn(`Unable to add response to browser cache: ${G}.`)}):await B.put(Q,ae,E.progress_callback)),(0,o.dispatchCallback)(E.progress_callback,{status:"done",name:T,file:g}),R){if(k)throw new Error("Cannot return path in a browser environment.");return R}if(ae instanceof d)return ae.filePath;const O=await B.match(Q);if(O instanceof d)return O.filePath;throw new Error("Unable to return path for response.")}async function b(T,g,M=!0,E={}){const k=await A(T,g,M,E,!1);if(k===null)return{};const N=new TextDecoder("utf-8").decode(k);return JSON.parse(N)}async function y(T,g){const M=T.headers.get("Content-Length");M===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let E=parseInt(M??"0"),k=new Uint8Array(E),B=0;const N=T.body.getReader();async function J(){const{done:q,value:V}=await N.read();if(q)return;const Y=B+V.length;if(Y>E){E=Y;const Q=new Uint8Array(E);Q.set(k),k=Q}k.set(V,B),B=Y;const H=B/E*100;return g({progress:H,loaded:B,total:E}),J()}return await J(),k}function $(...T){return T=T.map((g,M)=>(M&&(g=g.replace(new RegExp("^/"),"")),M!==T.length-1&&(g=g.replace(new RegExp("/$"),"")),g)),T.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>f,load_image:()=>P});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js"),n=t("./src/env.js"),o=t("./src/utils/tensor.js"),a=t("?2b25");let l,d,p;const u=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(u)l=(A,b)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(A,b)},p=self.createImageBitmap,d=self.ImageData;else if(a)p=async A=>{const y=(await A.metadata()).channels,{data:$,info:T}=await A.rotate().raw().toBuffer({resolveWithObject:!0}),g=new f(new Uint8ClampedArray($),T.width,T.height,T.channels);return y!==void 0&&y!==T.channels&&g.convert(y),g};else throw new Error("Unable to load image processing library.");const h={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},w=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(b,y,$,T){this.data=b,this.width=y,this.height=$,this.channels=T}get size(){return[this.width,this.height]}static async read(b){if(b instanceof f)return b;if(typeof b=="string"||b instanceof URL)return await this.fromURL(b);if(b instanceof Blob)return await this.fromBlob(b);if(typeof HTMLCanvasElement<"u"&&b instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&b instanceof OffscreenCanvas)return this.fromCanvas(b);throw new Error(`Unsupported input type: ${typeof b}`)}static fromCanvas(b){if(!u)throw new Error("fromCanvas() is only supported in browser environments.");const $=b.getContext("2d").getImageData(0,0,b.width,b.height).data;return new f($,b.width,b.height,4)}static async fromURL(b){const y=await(0,i.getFile)(b);if(y.status!==200)throw new Error(`Unable to read image from "${b}" (${y.status} ${y.statusText})`);const $=await y.blob();return this.fromBlob($)}static async fromBlob(b){if(u){const y=await p(b),$=l(y.width,y.height).getContext("2d");return $.drawImage(y,0,0),new this($.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=a(await b.arrayBuffer());return await p(y)}}static fromTensor(b,y="CHW"){if(b.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${b.dims.length} dimensions.`);if(y==="CHW")b=b.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(b.data instanceof Uint8ClampedArray||b.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${b.type}`);switch(b.dims[2]){case 1:case 2:case 3:case 4:return new f(b.data,b.dims[1],b.dims[0],b.dims[2]);default:throw new Error(`Unsupported number of channels: ${b.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const b=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,$=0;y=0?k=$:N=-$,T>=0?B=T:J=-T,E.drawImage(M,k,B,b,y,N,J,b,y),new f(E.getImageData(0,0,b,y).data,b,y,4).convert(g)}else{let g=this.toSharp();if($>=0&&T>=0)g=g.extract({left:Math.floor($),top:Math.floor(T),width:b,height:y});else if($<=0&&T<=0){const M=Math.floor(-T),E=Math.floor(-$);g=g.extend({top:M,left:E,right:b-this.width-E,bottom:y-this.height-M})}else{let M=[0,0],E=0;T<0?(M[0]=Math.floor(-T),M[1]=y-this.height-M[0]):E=Math.floor(T);let k=[0,0],B=0;$<0?(k[0]=Math.floor(-$),k[1]=b-this.width-k[0]):B=Math.floor($),g=g.extend({top:M[0],bottom:M[1],left:k[0],right:k[1]}).extract({left:B,top:E,width:b,height:y})}return await p(g)}}async toBlob(b="image/png",y=1){if(!u)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:b,quality:y})}toTensor(b="CHW"){let y=new o.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(b!=="HWC")if(b==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${b}`);return y}toCanvas(){if(!u)throw new Error("toCanvas() is only supported in browser environments.");const b=this.clone().rgba(),y=l(b.width,b.height),$=new d(b.data,b.width,b.height);return y.getContext("2d").putImageData($,0,0),y}split(){const{data:b,width:y,height:$,channels:T}=this,g=b.constructor,M=b.length/T,E=Array.from({length:T},()=>new g(M));for(let k=0;knew f(k,y,$,1))}_update(b,y,$,T=null){return this.data=b,this.width=y,this.height=$,T!==null&&(this.channels=T),this}clone(){return new f(this.data.slice(),this.width,this.height,this.channels)}convert(b){if(this.channels===b)return this;switch(b){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(b){if(u){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const y=b.split(".").pop().toLowerCase(),$=w.get(y)??"image/png",T=await this.toBlob($);(0,s.saveBlob)(b,T)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(b);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(u)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const P=f.read.bind(f)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>P,bankers_round:()=>y,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>$,interpolate_data:()=>s,log_softmax:()=>o,magnitude:()=>d,max:()=>u,medianFilter:()=>A,min:()=>p,permute_data:()=>i,round:()=>b,softmax:()=>n});function s(T,[g,M,E],[k,B],N="bilinear",J=!1){const q=B/E,V=k/M,Y=new T.constructor(k*B*g),H=M*E,Q=k*B;for(let ie=0;ie=0;--J)k[J]=q,E[J]=g[M[J]],q*=E[J];const B=M.map((J,q)=>k[M.indexOf(q)]),N=new T.constructor(T.length);for(let J=0;J=0;--V)q+=Y%g[V]*B[V],Y=Math.floor(Y/g[V]);N[q]=T[J]}return[N,E]}function n(T){const g=u(T)[0],M=T.map(B=>Math.exp(B-g)),E=M.reduce((B,N)=>B+N,0);return M.map(B=>B/E)}function o(T){const g=u(T)[0];let M=0;for(let B=0;BB-g-E)}function a(T,g){let M=0;for(let E=0;Eg+M*M,0))}function p(T){if(T.length===0)throw Error("Array must not be empty");let g=T[0],M=0;for(let E=1;Eg&&(g=T[E],M=E);return[g,M]}function h(T){return T>0&&(T&T-1)===0}class w{constructor(g){if(this.size=g|0,this.size<=1||!h(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=g<<1,this.table=new Float64Array(this.size*2);for(let E=0;EE;E<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=g[k];return E}toComplexArray(g,M){const E=M||this.createComplexArray();for(let k=0;k>>1],E[k+1]=0;return E}transform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._transform4(g,M,1)}realTransform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._realTransform4(g,M,1)}inverseTransform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._transform4(g,M,-1);for(let E=0;E>=2;N>=2;N>>=2){J=k/N<<1;const Q=J>>>2;for(q=0;q>>1,N>>>1)}else for(q=0,V=0;q>>1,N>>>1,E)}const H=this.table;for(N>>=2;N>=2;N>>=2){J=k/N<<1;const ie=J>>>1,le=ie>>>1,ae=le>>>1;for(q=0;q>>1;for(let ie=2;ie>1;++Y){const H=(Y+1-g)**2/2,Q=Math.sqrt(q**2+V**2)**H,ie=H*Math.atan2(V,q),le=2*Y;B[le]=Q*Math.cos(ie),B[le+1]=Q*Math.sin(ie),N[le]=B[le],N[le+1]=-B[le+1]}this._slicedChirpBuffer=B.subarray(M,E),this._f=new w(k>>1),this._f.transform(this._chirpBuffer,N)}_transform(g,M,E){const k=this._buffer1,B=this._buffer2,N=this._outBuffer1,J=this._outBuffer2,q=this._chirpBuffer,V=this._slicedChirpBuffer,Y=this._a;if(E)for(let H=0;H>1,le=M[ie];k[H]=le*V[H],k[Q]=le*V[Q]}else for(let H=0;H=T.length&&(q=2*(T.length-1)-q),E[N++]=T[q]}E.sort(),M[B]=E[k]}return M}function b(T,g){const M=Math.pow(10,g);return Math.round(T*M)/M}function y(T){const g=Math.round(T);return Math.abs(T)%1===.5?g%2===0?g:g-1:g}function $(T){const g=T.length,M=T[0].length,E=[g+1,M+1],k=Array.from({length:E[0]},()=>Array(E[1]).fill(1/0));k[0][0]=0;const B=Array.from({length:E[0]},()=>Array(E[1]).fill(-1));for(let Y=1;Y0||J>0;)switch(q.push(N-1),V.push(J-1),B[N][J]){case 0:--N,--J;break;case 1:--N;break;case 2:--J;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${N}, ${J}]. Please file a bug report.`)}return q.reverse(),V.reverse(),[q,V]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>o,Tensor:()=>a,cat:()=>M,full:()=>V,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>u,layer_norm:()=>y,matmul:()=>h,mean:()=>N,mean_pooling:()=>b,ones:()=>H,ones_like:()=>Q,permute:()=>d,quantize_embeddings:()=>we,rand:()=>ae,rfft:()=>w,slice:()=>A,stack:()=>E,std_mean:()=>B,topk:()=>f,zeros:()=>ie,zeros_like:()=>le});var s=t("./src/utils/maths.js"),i=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const o=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...O){re(this,"ort_tensor");return(0,i.isONNXTensor)(O[0])?this.ort_tensor=O[0]:this.ort_tensor=new i.Tensor(O[0],O[1],O[2]),new Proxy(this,{get:(G,ne)=>{if(typeof ne=="string"){let X=Number(ne);if(Number.isInteger(X))return G._getitem(X)}return G[ne]},set:(G,ne,X)=>G[ne]=X})}get dims(){return this.ort_tensor.dims}set dims(O){this.ort_tensor.dims=O}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[O,...G]=this.dims;if(G.length>0){const ne=G.reduce((X,ye)=>X*ye);for(let X=0;X0){const X=ne.reduce((ye,_e)=>ye*_e);return this._subarray(O,X,ne)}else return new a(this.type,[this.data[O]],ne)}indexOf(O){const G=this.data;for(let ne=0;nepe)throw new Error(`Invalid slice: ${K}`);const Pe=[Math.max(U,0),Math.min(pe,this.dims[Me])];ne.push(Pe),G.push(Pe[1]-Pe[0])}else throw new Error(`Invalid slice: ${K}`)}const X=ne.map(([Me,K])=>K-Me),ye=X.reduce((Me,K)=>Me*K),_e=this.data,ke=new _e.constructor(ye),He=this.stride();for(let Me=0;Me=0;--U){const Pe=X[U];K+=(pe%Pe+ne[U][0])*He[U],pe=Math.floor(pe/Pe)}ke[Me]=_e[K]}return new a(this.type,ke,G)}permute(...O){return d(this,O)}transpose(...O){return this.permute(...O)}sum(O=null,G=!1){return this.norm(1,O,G)}norm(O="fro",G=null,ne=!1){if(O==="fro")O=2;else if(typeof O=="string")throw Error(`Unsupported norm: ${O}`);const X=this.data,ye=(Me,K)=>Me+K**O;if(G===null){const Me=X.reduce(ye,0)**(1/O);return new a(this.type,[Me],[])}const[_e,ke,He]=k(ye,this,G,ne);if(O!==1)for(let Me=0;Me=0;--He){const U=this.dims[He];if(He!==G){const pe=Me%U;ke+=pe*K,K*=this.dims[He]}Me=Math.floor(Me/U)}X[_e]/=ye[ke]}return this}normalize(O=2,G=1){return this.clone().normalize_(O,G)}stride(){return J(this.dims)}squeeze(O=null){return new a(this.type,this.data,$(this.dims,O))}squeeze_(O=null){return this.dims=$(this.dims,O),this}unsqueeze(O=null){return new a(this.type,this.data,T(this.dims,O))}unsqueeze_(O=null){return this.dims=T(this.dims,O),this}flatten_(O=0,G=-1){G=(G+this.dims.length)%this.dims.length;let ne=this.dims.slice(0,O),X=this.dims.slice(O,G+1),ye=this.dims.slice(G+1);return this.dims=[...ne,X.reduce((_e,ke)=>_e*ke,1),...ye],this}flatten(O=0,G=-1){return this.clone().flatten_(O,G)}view(...O){let G=-1;for(let X=0;Xke!==G?ye*_e:ye,1);O[G]=ne.length/X}return new a(this.type,ne,O)}neg_(){const O=this.data;for(let G=0;GO?1:0;return new a("bool",G,this.dims)}lt(O){const G=new Uint8Array(this.data.length),ne=this.data;for(let X=0;XMath.min(_e,ke),this,O,G,1/0);return new a(ne,X,ye)}max(O=null,G=!1){if(O===null){const _e=(0,s.max)(this.data)[0];return new a(this.type,[_e],[])}const[ne,X,ye]=k((_e,ke)=>Math.max(_e,ke),this,O,G,-1/0);return new a(ne,X,ye)}argmin(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const ne=(0,s.min)(this.data)[1];return new a("int64",[BigInt(ne)],[])}argmax(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const ne=(0,s.max)(this.data)[1];return new a("int64",[BigInt(ne)],[])}to(O){if(this.type===O)return this;if(!o.hasOwnProperty(O))throw new Error(`Unsupported type: ${O}`);let G;const ne=["int64","uint64"].includes(this.type),X=["int64","uint64"].includes(O);return ne&&!X?G=Number:!ne&&X&&(G=BigInt),new a(O,o[O].from(this.data,G),this.dims)}}function l(R,O){const G=R.length,ne=O.reduce((ye,_e)=>ye*_e);if(G!==ne)throw Error(`cannot reshape array of size ${G} into shape (${O})`);let X=R;for(let ye=O.length-1;ye>=0;ye--)X=X.reduce((_e,ke)=>{let He=_e[_e.length-1];return He.lengthnew a("int64",R,[R.length]);async function A(R,O,G,ne,X){return await(await n.TensorOpRegistry.slice)({x:R,s:P(O),e:P(G),a:P(ne),t:P(X??new Array(ne.length).fill(1))})}function b(R,O){const G=R.data,ne=O.data,X=[R.dims[0],R.dims[2]],ye=new G.constructor(X[0]*X[1]),[_e,ke,He]=R.dims;let Me=0;for(let K=0;K<_e;++K){const U=K*He*ke;for(let pe=0;peG!==1):typeof O=="number"?R[O]===1&&R.splice(O,1):Array.isArray(O)&&(R=R.filter((G,ne)=>G!==1||!O.includes(ne))),R}function T(R,O){return O=g(O,R.length+1),R=R.slice(),R.splice(O,0,1),R}function g(R,O,G=null,ne=!0){if(R<-O||R>=O){if(ne)throw new Error(`IndexError: index ${R} is out of bounds for dimension${G===null?"":" "+G} with size ${O}`);return R<-O?0:O}return R<0&&(R=(R%O+O)%O),R}function M(R,O=0){O=g(O,R[0].dims.length);const G=R[0].dims.slice();G[O]=R.reduce((_e,ke)=>_e+ke.dims[O],0);const ne=G.reduce((_e,ke)=>_e*ke,1),X=new R[0].data.constructor(ne),ye=R[0].type;if(O===0){let _e=0;for(const ke of R){const He=ke.data;X.set(He,_e),_e+=He.length}}else{let _e=0;for(let ke=0;ke=0;--pe){const Ae=Me[pe];let Ie=Pe%Ae;pe===O&&(Ie+=_e),U+=Ie*Te,Te*=G[pe],Pe=Math.floor(Pe/Ae)}X[U]=He[K]}_e+=Me[O]}}return new a(ye,X,G)}function E(R,O=0){return M(R.map(G=>G.unsqueeze(O)),O)}function k(R,O,G=null,ne=!1,X=null){const ye=O.data,_e=O.dims;G=g(G,_e.length);const ke=_e.slice();ke[G]=1;const He=new ye.constructor(ye.length/_e[G]);X!==null&&He.fill(X);for(let Me=0;Me=0;--U){const Te=_e[U];if(U!==G){const Ae=pe%Te;K+=Ae*Pe,Pe*=ke[U]}pe=Math.floor(pe/Te)}He[K]=R(He[K],ye[Me],Me,K)}return ne||ke.splice(G,1),[O.type,He,ke]}function B(R,O=null,G=1,ne=!1){const X=R.data,ye=R.dims;if(O===null){const Pe=X.reduce((Le,Ne)=>Le+Ne,0)/X.length,Te=Math.sqrt(X.reduce((Le,Ne)=>Le+(Ne-Pe)**2,0)/(X.length-G)),Ae=new a(R.type,[Pe],[]);return[new a(R.type,[Te],[]),Ae]}O=g(O,ye.length);const _e=N(R,O,ne),ke=_e.data,[He,Me,K]=k((pe,Pe,Te,Ae)=>pe+(Pe-ke[Ae])**2,R,O,ne);for(let pe=0;peMe+K,0);return new a(R.type,[He/X.length],[])}O=g(O,ne.length);const[ye,_e,ke]=k((He,Me)=>He+Me,R,O,G);if(ne[O]!==1)for(let He=0;He<_e.length;++He)_e[He]/=ne[O];return new a(ye,_e,ke)}function J(R){const O=new Array(R.length);for(let G=R.length-1,ne=1;G>=0;--G)O[G]=ne,ne*=R[G];return O}function q(R,O,G,ne){const X=R.reduce((ye,_e)=>ye*_e,1);return new a(G,new ne(X).fill(O),R)}function V(R,O){let G,ne;if(typeof O=="number")G="float32",ne=Float32Array;else if(typeof O=="bigint")G="int64",ne=BigInt64Array;else if(typeof O=="boolean")G="bool",ne=Uint8Array;else throw new Error(`Unsupported data type: ${typeof O}`);return q(R,O,G,ne)}function Y(R,O){return V(R.dims,O)}function H(R){return q(R,1n,"int64",BigInt64Array)}function Q(R){return H(R.dims)}function ie(R){return q(R,0n,"int64",BigInt64Array)}function le(R){return ie(R.dims)}function ae(R){const O=R.reduce((G,ne)=>G*ne,1);return new a("float32",Float32Array.from({length:O},()=>Math.random()),R)}function we(R,O){if(R.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(R.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(O))throw new Error("The precision must be either 'binary' or 'ubinary'");const G=O==="binary",ne=G?"int8":"uint8",X=G?Int8Array:Uint8Array,ye=R.data,_e=new X(ye.length/8);for(let ke=0;ke0?1:0,Me=Math.floor(ke/8),K=ke%8;_e[Me]|=He<<7-K,G&&K===0&&(_e[Me]-=128)}return new a(ne,_e,[R.dims[0],R.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>o,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),i=t("./src/env.js");class n{constructor(d,p){this.image=d,this.timestamp=p}}class o{constructor(d,p){d.length>0&&d[0]instanceof s.RawImage&&(d=d.map((u,h)=>new n(u,(h+1)/(d.length+1)*p))),this.frames=d,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:d=null,fps:p=null}={}){if(!i.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(d==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const u=[],h=document.createElement("video");if(h.crossOrigin="anonymous",h.muted=!0,typeof l=="string")h.src=l;else if(l instanceof Blob)h.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)h.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise($=>h.onloadedmetadata=$),h.seekable.start(0)===h.seekable.end(0)){const T=await(await fetch(h.src)).blob();h.src=URL.createObjectURL(T),await new Promise(g=>h.onloadedmetadata=g)}const w=h.duration;let f,P;d!=null?(f=d,P=d===1?0:w/(d-1)):(P=1/p,f=Math.floor(w/P));let A=[];for(let $=0;${h.onseeked=E}),y.drawImage(h,0,0,b.width,b.height);const T=y.getImageData(0,0,b.width,b.height),g=new s.RawImage(T.data,b.width,b.height,4),M=new n(g,$);u.push(M)}return h.remove(),new o(u,w)}}},Hw={};function Ft(e){var r=Hw[e];if(r!==void 0)return r.exports;var t=Hw[e]={exports:{}};return sx[e](t,t.exports,Ft),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Ft.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var i=Object.create(null);Ft.r(i);var n={};r=r||[null,e({}),e([]),e(e)];for(var o=s&2&&t;typeof o=="object"&&!~r.indexOf(o);o=e(o))Object.getOwnPropertyNames(o).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Ft.d(i,n),i}})(),Ft.d=(e,r)=>{for(var t in r)Ft.o(r,t)&&!Ft.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Ft.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Ft.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var _={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! - \*****************************/Ft.r(f),Ft.d(f,{ASTFeatureExtractor:()=>u.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>i.AutoConfig,AutoFeatureExtractor:()=>h.AutoFeatureExtractor,AutoImageProcessor:()=>P.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>y.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>S.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>u.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>g.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>u.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>u.EncodecFeatureExtractor,EosTokenCriteria:()=>x.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>d.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>v.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>g.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>g.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>v.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>v.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>u.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>w.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>x.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>v.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>g.LogitsProcessor,LogitsProcessorList:()=>g.LogitsProcessorList,LogitsWarper:()=>g.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>x.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>v.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>g.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>g.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>u.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>v.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>g.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>g.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>v.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>v.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>v.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>i.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>A.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>u.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>v.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>v.Qwen2VLProcessor,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>o.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>g.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>v.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>v.SmolVLMProcessor,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>v.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>x.StoppingCriteria,StoppingCriteriaList:()=>x.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>g.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>g.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>S.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>g.TopKLogitsWarper,TopPLogitsWarper:()=>g.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>v.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>v.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>u.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>v.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>v.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>u.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>u.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>v.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>g.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>d.bankers_round,cat:()=>l.cat,cos_sim:()=>d.cos_sim,dot:()=>d.dot,dynamic_time_warping:()=>d.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>i.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>d.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>o.load_image,load_video:()=>a.load_video,log_softmax:()=>d.log_softmax,magnitude:()=>d.magnitude,matmul:()=>l.matmul,max:()=>d.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>d.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>d.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>d.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>d.round,slice:()=>l.slice,softmax:()=>d.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Ft("./src/env.js"),r=Ft("./src/pipelines.js"),t=Ft("./src/models.js"),s=Ft("./src/tokenizers.js"),i=Ft("./src/configs.js"),n=Ft("./src/utils/audio.js"),o=Ft("./src/utils/image.js"),a=Ft("./src/utils/video.js"),l=Ft("./src/utils/tensor.js"),d=Ft("./src/utils/maths.js"),p=Ft("./src/base/feature_extraction_utils.js"),u=Ft("./src/models/feature_extractors.js"),h=Ft("./src/models/auto/feature_extraction_auto.js"),w=Ft("./src/base/image_processors_utils.js"),_=Ft("./src/models/image_processors.js"),P=Ft("./src/models/auto/image_processing_auto.js"),A=Ft("./src/base/processing_utils.js"),v=Ft("./src/models/processors.js"),y=Ft("./src/models/auto/processing_auto.js"),S=Ft("./src/generation/streamers.js"),x=Ft("./src/generation/stopping_criteria.js"),g=Ft("./src/generation/logits_process.js")})(),f.ASTFeatureExtractor,f.ASTForAudioClassification,f.ASTModel,f.ASTPreTrainedModel,f.AlbertForMaskedLM,f.AlbertForQuestionAnswering,f.AlbertForSequenceClassification,f.AlbertModel,f.AlbertPreTrainedModel,f.AlbertTokenizer,f.AudioClassificationPipeline,f.AutoConfig,f.AutoFeatureExtractor,f.AutoImageProcessor,f.AutoModel,f.AutoModelForAudioClassification,f.AutoModelForAudioFrameClassification,f.AutoModelForAudioTextToText,f.AutoModelForCTC,f.AutoModelForCausalLM,f.AutoModelForDepthEstimation,f.AutoModelForDocumentQuestionAnswering,f.AutoModelForImageClassification,f.AutoModelForImageFeatureExtraction,f.AutoModelForImageMatting,f.AutoModelForImageSegmentation,f.AutoModelForImageTextToText,f.AutoModelForImageToImage,f.AutoModelForMaskGeneration,f.AutoModelForMaskedLM,f.AutoModelForNormalEstimation,f.AutoModelForObjectDetection,f.AutoModelForPoseEstimation,f.AutoModelForQuestionAnswering,f.AutoModelForSemanticSegmentation,f.AutoModelForSeq2SeqLM,f.AutoModelForSequenceClassification,f.AutoModelForSpeechSeq2Seq,f.AutoModelForTextToSpectrogram,f.AutoModelForTextToWaveform,f.AutoModelForTokenClassification,f.AutoModelForUniversalSegmentation,f.AutoModelForVision2Seq,f.AutoModelForXVector,f.AutoModelForZeroShotObjectDetection;var Hv=f.AutoProcessor,qv=f.AutoTokenizer;f.AutomaticSpeechRecognitionPipeline,f.BackgroundRemovalPipeline,f.BartForConditionalGeneration,f.BartForSequenceClassification,f.BartModel,f.BartPretrainedModel,f.BartTokenizer,f.BaseModelOutput,f.BaseStreamer,f.BeitFeatureExtractor,f.BeitForImageClassification,f.BeitModel,f.BeitPreTrainedModel,f.BertForMaskedLM,f.BertForQuestionAnswering,f.BertForSequenceClassification,f.BertForTokenClassification,f.BertModel,f.BertPreTrainedModel,f.BertTokenizer,f.BitImageProcessor,f.BlenderbotForConditionalGeneration,f.BlenderbotModel,f.BlenderbotPreTrainedModel,f.BlenderbotSmallForConditionalGeneration,f.BlenderbotSmallModel,f.BlenderbotSmallPreTrainedModel,f.BlenderbotSmallTokenizer,f.BlenderbotTokenizer,f.BloomForCausalLM,f.BloomModel,f.BloomPreTrainedModel,f.BloomTokenizer,f.CLIPFeatureExtractor,f.CLIPImageProcessor,f.CLIPModel,f.CLIPPreTrainedModel,f.CLIPSegForImageSegmentation,f.CLIPSegModel,f.CLIPSegPreTrainedModel,f.CLIPTextModel,f.CLIPTextModelWithProjection,f.CLIPTokenizer,f.CLIPVisionModel,f.CLIPVisionModelWithProjection,f.CamembertForMaskedLM,f.CamembertForQuestionAnswering,f.CamembertForSequenceClassification,f.CamembertForTokenClassification,f.CamembertModel,f.CamembertPreTrainedModel,f.CamembertTokenizer,f.CausalLMOutput,f.CausalLMOutputWithPast,f.ChineseCLIPFeatureExtractor,f.ChineseCLIPModel,f.ChineseCLIPPreTrainedModel,f.ClapAudioModelWithProjection,f.ClapFeatureExtractor,f.ClapModel,f.ClapPreTrainedModel,f.ClapTextModelWithProjection,f.ClassifierFreeGuidanceLogitsProcessor,f.CodeGenForCausalLM,f.CodeGenModel,f.CodeGenPreTrainedModel,f.CodeGenTokenizer,f.CodeLlamaTokenizer,f.CohereForCausalLM,f.CohereModel,f.CoherePreTrainedModel,f.CohereTokenizer,f.ConvBertForMaskedLM,f.ConvBertForQuestionAnswering,f.ConvBertForSequenceClassification,f.ConvBertForTokenClassification,f.ConvBertModel,f.ConvBertPreTrainedModel,f.ConvBertTokenizer,f.ConvNextFeatureExtractor,f.ConvNextForImageClassification,f.ConvNextImageProcessor,f.ConvNextModel,f.ConvNextPreTrainedModel,f.ConvNextV2ForImageClassification,f.ConvNextV2Model,f.ConvNextV2PreTrainedModel,f.DPTFeatureExtractor,f.DPTForDepthEstimation,f.DPTImageProcessor,f.DPTModel,f.DPTPreTrainedModel,f.DacDecoderModel,f.DacDecoderOutput,f.DacEncoderModel,f.DacEncoderOutput,f.DacFeatureExtractor,f.DacModel,f.DacPreTrainedModel,f.DataTypeMap,f.DebertaForMaskedLM,f.DebertaForQuestionAnswering,f.DebertaForSequenceClassification,f.DebertaForTokenClassification,f.DebertaModel,f.DebertaPreTrainedModel,f.DebertaTokenizer,f.DebertaV2ForMaskedLM,f.DebertaV2ForQuestionAnswering,f.DebertaV2ForSequenceClassification,f.DebertaV2ForTokenClassification,f.DebertaV2Model,f.DebertaV2PreTrainedModel,f.DebertaV2Tokenizer,f.DecisionTransformerModel,f.DecisionTransformerPreTrainedModel,f.DeiTFeatureExtractor,f.DeiTForImageClassification,f.DeiTImageProcessor,f.DeiTModel,f.DeiTPreTrainedModel,f.DepthAnythingForDepthEstimation,f.DepthAnythingPreTrainedModel,f.DepthEstimationPipeline,f.DepthProForDepthEstimation,f.DepthProPreTrainedModel,f.DetrFeatureExtractor,f.DetrForObjectDetection,f.DetrForSegmentation,f.DetrImageProcessor,f.DetrModel,f.DetrObjectDetectionOutput,f.DetrPreTrainedModel,f.DetrSegmentationOutput,f.Dinov2ForImageClassification,f.Dinov2Model,f.Dinov2PreTrainedModel,f.Dinov2WithRegistersForImageClassification,f.Dinov2WithRegistersModel,f.Dinov2WithRegistersPreTrainedModel,f.DistilBertForMaskedLM,f.DistilBertForQuestionAnswering,f.DistilBertForSequenceClassification,f.DistilBertForTokenClassification,f.DistilBertModel,f.DistilBertPreTrainedModel,f.DistilBertTokenizer,f.DocumentQuestionAnsweringPipeline,f.DonutFeatureExtractor,f.DonutImageProcessor,f.DonutSwinModel,f.DonutSwinPreTrainedModel,f.EfficientNetForImageClassification,f.EfficientNetImageProcessor,f.EfficientNetModel,f.EfficientNetPreTrainedModel,f.ElectraForMaskedLM,f.ElectraForQuestionAnswering,f.ElectraForSequenceClassification,f.ElectraForTokenClassification,f.ElectraModel,f.ElectraPreTrainedModel,f.ElectraTokenizer,f.EncodecFeatureExtractor,f.EosTokenCriteria,f.EsmForMaskedLM,f.EsmForSequenceClassification,f.EsmForTokenClassification,f.EsmModel,f.EsmPreTrainedModel,f.EsmTokenizer,f.ExaoneForCausalLM,f.ExaoneModel,f.ExaonePreTrainedModel,f.FFT,f.FalconForCausalLM,f.FalconModel,f.FalconPreTrainedModel,f.FalconTokenizer,f.FastViTForImageClassification,f.FastViTModel,f.FastViTPreTrainedModel,f.FeatureExtractionPipeline,f.FeatureExtractor,f.FillMaskPipeline,f.Florence2ForConditionalGeneration,f.Florence2PreTrainedModel,f.Florence2Processor,f.ForcedBOSTokenLogitsProcessor,f.ForcedEOSTokenLogitsProcessor,f.GLPNFeatureExtractor,f.GLPNForDepthEstimation,f.GLPNModel,f.GLPNPreTrainedModel,f.GPT2LMHeadModel,f.GPT2Model,f.GPT2PreTrainedModel,f.GPT2Tokenizer,f.GPTBigCodeForCausalLM,f.GPTBigCodeModel,f.GPTBigCodePreTrainedModel,f.GPTJForCausalLM,f.GPTJModel,f.GPTJPreTrainedModel,f.GPTNeoForCausalLM,f.GPTNeoModel,f.GPTNeoPreTrainedModel,f.GPTNeoXForCausalLM,f.GPTNeoXModel,f.GPTNeoXPreTrainedModel,f.GPTNeoXTokenizer,f.Gemma2ForCausalLM,f.Gemma2Model,f.Gemma2PreTrainedModel,f.GemmaForCausalLM,f.GemmaModel,f.GemmaPreTrainedModel,f.GemmaTokenizer,f.GlmForCausalLM,f.GlmModel,f.GlmPreTrainedModel,f.GraniteForCausalLM,f.GraniteModel,f.GranitePreTrainedModel,f.Grok1Tokenizer,f.GroundingDinoForObjectDetection,f.GroundingDinoImageProcessor,f.GroundingDinoPreTrainedModel,f.GroundingDinoProcessor,f.GroupViTModel,f.GroupViTPreTrainedModel,f.HeliumForCausalLM,f.HeliumModel,f.HeliumPreTrainedModel,f.HerbertTokenizer,f.HieraForImageClassification,f.HieraModel,f.HieraPreTrainedModel,f.HubertForCTC,f.HubertForSequenceClassification,f.HubertModel,f.HubertPreTrainedModel,f.IJepaForImageClassification,f.IJepaModel,f.IJepaPreTrainedModel,f.Idefics3ForConditionalGeneration,f.Idefics3ImageProcessor,f.Idefics3PreTrainedModel,f.Idefics3Processor,f.ImageClassificationPipeline,f.ImageFeatureExtractionPipeline,f.ImageFeatureExtractor,f.ImageMattingOutput,f.ImageProcessor,f.ImageSegmentationPipeline,f.ImageToImagePipeline,f.ImageToTextPipeline,f.InterruptableStoppingCriteria,f.JAISLMHeadModel,f.JAISModel,f.JAISPreTrainedModel,f.JinaCLIPImageProcessor,f.JinaCLIPModel,f.JinaCLIPPreTrainedModel,f.JinaCLIPProcessor,f.JinaCLIPTextModel,f.JinaCLIPVisionModel,f.LiteWhisperForConditionalGeneration,f.LlamaForCausalLM,f.LlamaModel,f.LlamaPreTrainedModel,f.LlamaTokenizer,f.LlavaForConditionalGeneration,f.LlavaOnevisionForConditionalGeneration,f.LlavaOnevisionImageProcessor,f.LlavaPreTrainedModel,f.LogitsProcessor,f.LogitsProcessorList,f.LogitsWarper,f.LongT5ForConditionalGeneration,f.LongT5Model,f.LongT5PreTrainedModel,f.M2M100ForConditionalGeneration,f.M2M100Model,f.M2M100PreTrainedModel,f.M2M100Tokenizer,f.MBart50Tokenizer,f.MBartForCausalLM,f.MBartForConditionalGeneration,f.MBartForSequenceClassification,f.MBartModel,f.MBartPreTrainedModel,f.MBartTokenizer,f.MPNetForMaskedLM,f.MPNetForQuestionAnswering,f.MPNetForSequenceClassification,f.MPNetForTokenClassification,f.MPNetModel,f.MPNetPreTrainedModel,f.MPNetTokenizer,f.MT5ForConditionalGeneration,f.MT5Model,f.MT5PreTrainedModel,f.MarianMTModel,f.MarianModel,f.MarianPreTrainedModel,f.MarianTokenizer,f.Mask2FormerImageProcessor,f.MaskFormerFeatureExtractor,f.MaskFormerForInstanceSegmentation,f.MaskFormerImageProcessor,f.MaskFormerModel,f.MaskFormerPreTrainedModel,f.MaskedLMOutput,f.MaxLengthCriteria,f.MgpstrForSceneTextRecognition,f.MgpstrModelOutput,f.MgpstrPreTrainedModel,f.MgpstrProcessor,f.MgpstrTokenizer,f.MimiDecoderModel,f.MimiDecoderOutput,f.MimiEncoderModel,f.MimiEncoderOutput,f.MimiModel,f.MimiPreTrainedModel,f.MinLengthLogitsProcessor,f.MinNewTokensLengthLogitsProcessor,f.MistralForCausalLM,f.MistralModel,f.MistralPreTrainedModel,f.MobileBertForMaskedLM,f.MobileBertForQuestionAnswering,f.MobileBertForSequenceClassification,f.MobileBertModel,f.MobileBertPreTrainedModel,f.MobileBertTokenizer,f.MobileLLMForCausalLM,f.MobileLLMModel,f.MobileLLMPreTrainedModel,f.MobileNetV1FeatureExtractor,f.MobileNetV1ForImageClassification,f.MobileNetV1ForSemanticSegmentation,f.MobileNetV1ImageProcessor,f.MobileNetV1Model,f.MobileNetV1PreTrainedModel,f.MobileNetV2FeatureExtractor,f.MobileNetV2ForImageClassification,f.MobileNetV2ForSemanticSegmentation,f.MobileNetV2ImageProcessor,f.MobileNetV2Model,f.MobileNetV2PreTrainedModel,f.MobileNetV3FeatureExtractor,f.MobileNetV3ForImageClassification,f.MobileNetV3ForSemanticSegmentation,f.MobileNetV3ImageProcessor,f.MobileNetV3Model,f.MobileNetV3PreTrainedModel,f.MobileNetV4FeatureExtractor,f.MobileNetV4ForImageClassification,f.MobileNetV4ForSemanticSegmentation,f.MobileNetV4ImageProcessor,f.MobileNetV4Model,f.MobileNetV4PreTrainedModel,f.MobileViTFeatureExtractor,f.MobileViTForImageClassification,f.MobileViTImageProcessor,f.MobileViTModel,f.MobileViTPreTrainedModel,f.MobileViTV2ForImageClassification,f.MobileViTV2Model,f.MobileViTV2PreTrainedModel,f.ModelOutput,f.ModernBertForMaskedLM,f.ModernBertForSequenceClassification,f.ModernBertForTokenClassification,f.ModernBertModel,f.ModernBertPreTrainedModel,f.Moondream1ForConditionalGeneration,f.MoonshineFeatureExtractor,f.MoonshineForConditionalGeneration,f.MoonshineModel,f.MoonshinePreTrainedModel,f.MoonshineProcessor,f.MptForCausalLM,f.MptModel,f.MptPreTrainedModel,f.MultiModalityCausalLM,f.MultiModalityPreTrainedModel,f.MusicgenForCausalLM,f.MusicgenForConditionalGeneration,f.MusicgenModel,f.MusicgenPreTrainedModel,f.NllbTokenizer,f.NoBadWordsLogitsProcessor,f.NoRepeatNGramLogitsProcessor,f.NomicBertModel,f.NomicBertPreTrainedModel,f.NougatImageProcessor,f.NougatTokenizer,f.OPTForCausalLM,f.OPTModel,f.OPTPreTrainedModel,f.ObjectDetectionPipeline,f.Olmo2ForCausalLM,f.Olmo2Model,f.Olmo2PreTrainedModel,f.OlmoForCausalLM,f.OlmoModel,f.OlmoPreTrainedModel,f.OpenELMForCausalLM,f.OpenELMModel,f.OpenELMPreTrainedModel,f.OwlViTFeatureExtractor,f.OwlViTForObjectDetection,f.OwlViTImageProcessor,f.OwlViTModel,f.OwlViTPreTrainedModel,f.OwlViTProcessor,f.Owlv2ForObjectDetection,f.Owlv2ImageProcessor,f.Owlv2Model,f.Owlv2PreTrainedModel,f.PaliGemmaForConditionalGeneration,f.PaliGemmaPreTrainedModel,f.PaliGemmaProcessor,f.PatchTSMixerForPrediction,f.PatchTSMixerModel,f.PatchTSMixerPreTrainedModel,f.PatchTSTForPrediction,f.PatchTSTModel,f.PatchTSTPreTrainedModel,f.Phi3ForCausalLM,f.Phi3Model,f.Phi3PreTrainedModel,f.Phi3VForCausalLM,f.Phi3VImageProcessor,f.Phi3VPreTrainedModel,f.Phi3VProcessor,f.PhiForCausalLM,f.PhiModel,f.PhiPreTrainedModel,f.Pipeline,f.PreTrainedModel,f.PreTrainedTokenizer,f.PretrainedConfig,f.PretrainedMixin,f.Processor,f.PvtForImageClassification,f.PvtImageProcessor,f.PvtModel,f.PvtPreTrainedModel,f.PyAnnoteFeatureExtractor,f.PyAnnoteForAudioFrameClassification,f.PyAnnoteModel,f.PyAnnotePreTrainedModel,f.PyAnnoteProcessor,f.QuestionAnsweringModelOutput,f.QuestionAnsweringPipeline,f.Qwen2ForCausalLM,f.Qwen2Model,f.Qwen2PreTrainedModel,f.Qwen2Tokenizer,f.Qwen2VLForConditionalGeneration,f.Qwen2VLImageProcessor,f.Qwen2VLPreTrainedModel,f.Qwen2VLProcessor,f.RTDetrForObjectDetection,f.RTDetrImageProcessor,f.RTDetrModel,f.RTDetrObjectDetectionOutput,f.RTDetrPreTrainedModel,f.RawAudio,f.RawImage,f.RawVideo,f.RawVideoFrame,f.RepetitionPenaltyLogitsProcessor,f.ResNetForImageClassification,f.ResNetModel,f.ResNetPreTrainedModel,f.RoFormerForMaskedLM,f.RoFormerForQuestionAnswering,f.RoFormerForSequenceClassification,f.RoFormerForTokenClassification,f.RoFormerModel,f.RoFormerPreTrainedModel,f.RoFormerTokenizer,f.RobertaForMaskedLM,f.RobertaForQuestionAnswering,f.RobertaForSequenceClassification,f.RobertaForTokenClassification,f.RobertaModel,f.RobertaPreTrainedModel,f.RobertaTokenizer,f.SamImageProcessor,f.SamImageSegmentationOutput,f.SamModel,f.SamPreTrainedModel,f.SamProcessor,f.SapiensForDepthEstimation,f.SapiensForNormalEstimation,f.SapiensForSemanticSegmentation,f.SapiensPreTrainedModel,f.SeamlessM4TFeatureExtractor,f.SegformerFeatureExtractor,f.SegformerForImageClassification,f.SegformerForSemanticSegmentation,f.SegformerImageProcessor,f.SegformerModel,f.SegformerPreTrainedModel,f.Seq2SeqLMOutput,f.SequenceClassifierOutput,f.SiglipImageProcessor,f.SiglipModel,f.SiglipPreTrainedModel,f.SiglipTextModel,f.SiglipTokenizer,f.SiglipVisionModel,f.SmolVLMForConditionalGeneration,f.SmolVLMImageProcessor,f.SmolVLMProcessor,f.SpeechT5FeatureExtractor,f.SpeechT5ForSpeechToText,f.SpeechT5ForTextToSpeech,f.SpeechT5HifiGan,f.SpeechT5Model,f.SpeechT5PreTrainedModel,f.SpeechT5Processor,f.SpeechT5Tokenizer,f.SqueezeBertForMaskedLM,f.SqueezeBertForQuestionAnswering,f.SqueezeBertForSequenceClassification,f.SqueezeBertModel,f.SqueezeBertPreTrainedModel,f.SqueezeBertTokenizer,f.StableLmForCausalLM,f.StableLmModel,f.StableLmPreTrainedModel,f.Starcoder2ForCausalLM,f.Starcoder2Model,f.Starcoder2PreTrainedModel,f.StoppingCriteria,f.StoppingCriteriaList,f.StyleTextToSpeech2Model,f.StyleTextToSpeech2PreTrainedModel,f.SummarizationPipeline,f.SuppressTokensAtBeginLogitsProcessor,f.Swin2SRForImageSuperResolution,f.Swin2SRImageProcessor,f.Swin2SRModel,f.Swin2SRPreTrainedModel,f.SwinForImageClassification,f.SwinForSemanticSegmentation,f.SwinModel,f.SwinPreTrainedModel,f.T5ForConditionalGeneration,f.T5Model,f.T5PreTrainedModel,f.T5Tokenizer,f.TableTransformerForObjectDetection,f.TableTransformerModel,f.TableTransformerObjectDetectionOutput,f.TableTransformerPreTrainedModel,f.TemperatureLogitsWarper,f.Tensor,f.Text2TextGenerationPipeline,f.TextClassificationPipeline,f.TextGenerationPipeline;var Qv=f.TextStreamer;f.TextToAudioPipeline,f.TokenClassificationPipeline,f.TokenClassifierOutput,f.TokenizerModel,f.TopKLogitsWarper,f.TopPLogitsWarper,f.TrOCRForCausalLM,f.TrOCRPreTrainedModel,f.TranslationPipeline,f.UltravoxModel,f.UltravoxPreTrainedModel,f.UltravoxProcessor,f.UniSpeechForCTC,f.UniSpeechForSequenceClassification,f.UniSpeechModel,f.UniSpeechPreTrainedModel,f.UniSpeechSatForAudioFrameClassification,f.UniSpeechSatForCTC,f.UniSpeechSatForSequenceClassification,f.UniSpeechSatModel,f.UniSpeechSatPreTrainedModel,f.VLChatProcessor,f.VLMImageProcessor,f.ViTFeatureExtractor,f.ViTForImageClassification,f.ViTImageProcessor,f.ViTMAEModel,f.ViTMAEPreTrainedModel,f.ViTMSNForImageClassification,f.ViTMSNModel,f.ViTMSNPreTrainedModel,f.ViTModel,f.ViTPreTrainedModel,f.VisionEncoderDecoderModel,f.VitMatteForImageMatting,f.VitMatteImageProcessor,f.VitMattePreTrainedModel,f.VitPoseForPoseEstimation,f.VitPoseImageProcessor,f.VitPosePreTrainedModel,f.VitsModel,f.VitsModelOutput,f.VitsPreTrainedModel,f.VitsTokenizer,f.Wav2Vec2BertForCTC,f.Wav2Vec2BertForSequenceClassification,f.Wav2Vec2BertModel,f.Wav2Vec2BertPreTrainedModel,f.Wav2Vec2CTCTokenizer,f.Wav2Vec2FeatureExtractor,f.Wav2Vec2ForAudioFrameClassification,f.Wav2Vec2ForCTC,f.Wav2Vec2ForSequenceClassification,f.Wav2Vec2Model,f.Wav2Vec2PreTrainedModel,f.Wav2Vec2Processor,f.Wav2Vec2ProcessorWithLM,f.WavLMForAudioFrameClassification,f.WavLMForCTC,f.WavLMForSequenceClassification,f.WavLMForXVector,f.WavLMModel,f.WavLMPreTrainedModel,f.WeSpeakerFeatureExtractor,f.WeSpeakerResNetModel,f.WeSpeakerResNetPreTrainedModel,f.WhisperFeatureExtractor;var Xv=f.WhisperForConditionalGeneration;f.WhisperModel,f.WhisperPreTrainedModel,f.WhisperProcessor,f.WhisperTextStreamer,f.WhisperTimeStampLogitsProcessor,f.WhisperTokenizer,f.XLMForQuestionAnswering,f.XLMForSequenceClassification,f.XLMForTokenClassification,f.XLMModel,f.XLMPreTrainedModel,f.XLMRobertaForMaskedLM,f.XLMRobertaForQuestionAnswering,f.XLMRobertaForSequenceClassification,f.XLMRobertaForTokenClassification,f.XLMRobertaModel,f.XLMRobertaPreTrainedModel,f.XLMRobertaTokenizer,f.XLMTokenizer,f.XLMWithLMHeadModel,f.XVectorOutput,f.YolosFeatureExtractor,f.YolosForObjectDetection,f.YolosImageProcessor,f.YolosModel,f.YolosObjectDetectionOutput,f.YolosPreTrainedModel,f.ZeroShotAudioClassificationPipeline,f.ZeroShotClassificationPipeline,f.ZeroShotImageClassificationPipeline,f.ZeroShotObjectDetectionPipeline,f.bankers_round,f.cat,f.cos_sim,f.dot,f.dynamic_time_warping,f.env;var Jv=f.full;f.full_like,f.getKeyValueShapes,f.hamming,f.hanning,f.interpolate,f.interpolate_4d,f.interpolate_data,f.is_chinese_char,f.layer_norm,f.load_image,f.load_video,f.log_softmax,f.magnitude,f.matmul,f.max,f.mean,f.mean_pooling,f.medianFilter,f.mel_filter_bank,f.min,f.ones,f.ones_like,f.permute,f.permute_data,f.pipeline,f.quantize_embeddings,f.rand,f.read_audio,f.rfft,f.round,f.slice,f.softmax,f.spectrogram,f.stack,f.std_mean,f.topk,f.window_function,f.zeros,f.zeros_like;const Yv=64;class Wn{static async getInstance(r){return this.model_id="onnx-community/whisper-large-v3-turbo",this.tokenizer??(this.tokenizer=qv.from_pretrained(this.model_id,{progress_callback:r})),this.processor??(this.processor=Hv.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=Xv.from_pretrained(this.model_id,{dtype:{encoder_model:"fp16",decoder_model_merged:"q4"},device:"webgpu",progress_callback:r})),Promise.all([this.tokenizer,this.processor,this.model])}}re(Wn,"model_id",null),re(Wn,"tokenizer"),re(Wn,"processor"),re(Wn,"model");async function Zv(e){const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n{o??(o=performance.now());let _;a++>0&&(_=a/(performance.now()-o)*1e3),globalThis.postMessage({status:"update",output:w,tps:_,numTokens:a})},d=new Qv(s,{skip_prompt:!0,decode_kwargs:{skip_special_tokens:!0},callback_function:l}),p=await i(t),u=await n.generate({...p,max_new_tokens:Yv,language:r,streamer:d}),h=s.batch_decode(u,{skip_special_tokens:!0});globalThis.postMessage({status:"complete",output:h}),Qc=!1}async function tx(){globalThis.postMessage({status:"loading",data:"Loading model..."});const[e,r,t]=await Wn.getInstance(s=>{globalThis.postMessage(s)});globalThis.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await t.generate({input_features:Jv([1,128,3e3],0),max_new_tokens:1}),globalThis.postMessage({status:"ready"})}globalThis.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"load":tx();break;case"generate":ex(t);break}})})(); + \*****************************/Ft.r(_),Ft.d(_,{ASTFeatureExtractor:()=>u.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>i.AutoConfig,AutoFeatureExtractor:()=>h.AutoFeatureExtractor,AutoImageProcessor:()=>P.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>y.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>$.BaseStreamer,BeitFeatureExtractor:()=>f.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>f.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>f.CLIPFeatureExtractor,CLIPImageProcessor:()=>f.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>f.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>u.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>g.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>f.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>f.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>f.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>f.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>u.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>f.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>f.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>f.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>f.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>f.DonutFeatureExtractor,DonutImageProcessor:()=>f.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>f.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>u.EncodecFeatureExtractor,EosTokenCriteria:()=>T.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>d.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>b.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>g.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>g.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>b.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>f.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>b.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>u.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>w.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>T.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>b.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>f.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>g.LogitsProcessor,LogitsProcessorList:()=>g.LogitsProcessorList,LogitsWarper:()=>g.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>f.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>f.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>f.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>T.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>b.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>g.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>g.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>f.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>f.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>f.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>f.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>f.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>f.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>f.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>f.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>f.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>f.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>u.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>b.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>g.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>g.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>f.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>f.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>f.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>b.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>f.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>b.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>f.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>b.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>i.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>A.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>f.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>u.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>b.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>f.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>b.Qwen2VLProcessor,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>f.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>o.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>g.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>f.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>b.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>f.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>f.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>f.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>f.SmolVLMImageProcessor,SmolVLMProcessor:()=>b.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>u.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>b.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>T.StoppingCriteria,StoppingCriteriaList:()=>T.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>g.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>f.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>g.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>$.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>g.TopKLogitsWarper,TopPLogitsWarper:()=>g.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>b.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>b.VLChatProcessor,VLMImageProcessor:()=>f.VLMImageProcessor,ViTFeatureExtractor:()=>f.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>f.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>f.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>f.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>u.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>b.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>b.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>u.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>u.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>b.WhisperProcessor,WhisperTextStreamer:()=>$.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>g.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>f.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>f.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>d.bankers_round,cat:()=>l.cat,cos_sim:()=>d.cos_sim,dot:()=>d.dot,dynamic_time_warping:()=>d.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>i.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>d.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>o.load_image,load_video:()=>a.load_video,log_softmax:()=>d.log_softmax,magnitude:()=>d.magnitude,matmul:()=>l.matmul,max:()=>d.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>d.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>d.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>d.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>d.round,slice:()=>l.slice,softmax:()=>d.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Ft("./src/env.js"),r=Ft("./src/pipelines.js"),t=Ft("./src/models.js"),s=Ft("./src/tokenizers.js"),i=Ft("./src/configs.js"),n=Ft("./src/utils/audio.js"),o=Ft("./src/utils/image.js"),a=Ft("./src/utils/video.js"),l=Ft("./src/utils/tensor.js"),d=Ft("./src/utils/maths.js"),p=Ft("./src/base/feature_extraction_utils.js"),u=Ft("./src/models/feature_extractors.js"),h=Ft("./src/models/auto/feature_extraction_auto.js"),w=Ft("./src/base/image_processors_utils.js"),f=Ft("./src/models/image_processors.js"),P=Ft("./src/models/auto/image_processing_auto.js"),A=Ft("./src/base/processing_utils.js"),b=Ft("./src/models/processors.js"),y=Ft("./src/models/auto/processing_auto.js"),$=Ft("./src/generation/streamers.js"),T=Ft("./src/generation/stopping_criteria.js"),g=Ft("./src/generation/logits_process.js")})(),_.ASTFeatureExtractor,_.ASTForAudioClassification,_.ASTModel,_.ASTPreTrainedModel,_.AlbertForMaskedLM,_.AlbertForQuestionAnswering,_.AlbertForSequenceClassification,_.AlbertModel,_.AlbertPreTrainedModel,_.AlbertTokenizer,_.AudioClassificationPipeline,_.AutoConfig,_.AutoFeatureExtractor,_.AutoImageProcessor,_.AutoModel,_.AutoModelForAudioClassification,_.AutoModelForAudioFrameClassification,_.AutoModelForAudioTextToText,_.AutoModelForCTC,_.AutoModelForCausalLM,_.AutoModelForDepthEstimation,_.AutoModelForDocumentQuestionAnswering,_.AutoModelForImageClassification,_.AutoModelForImageFeatureExtraction,_.AutoModelForImageMatting,_.AutoModelForImageSegmentation,_.AutoModelForImageTextToText,_.AutoModelForImageToImage,_.AutoModelForMaskGeneration,_.AutoModelForMaskedLM,_.AutoModelForNormalEstimation,_.AutoModelForObjectDetection,_.AutoModelForPoseEstimation,_.AutoModelForQuestionAnswering,_.AutoModelForSemanticSegmentation,_.AutoModelForSeq2SeqLM,_.AutoModelForSequenceClassification,_.AutoModelForSpeechSeq2Seq,_.AutoModelForTextToSpectrogram,_.AutoModelForTextToWaveform,_.AutoModelForTokenClassification,_.AutoModelForUniversalSegmentation,_.AutoModelForVision2Seq,_.AutoModelForXVector,_.AutoModelForZeroShotObjectDetection;var nx=_.AutoProcessor,ix=_.AutoTokenizer;_.AutomaticSpeechRecognitionPipeline,_.BackgroundRemovalPipeline,_.BartForConditionalGeneration,_.BartForSequenceClassification,_.BartModel,_.BartPretrainedModel,_.BartTokenizer,_.BaseModelOutput,_.BaseStreamer,_.BeitFeatureExtractor,_.BeitForImageClassification,_.BeitModel,_.BeitPreTrainedModel,_.BertForMaskedLM,_.BertForQuestionAnswering,_.BertForSequenceClassification,_.BertForTokenClassification,_.BertModel,_.BertPreTrainedModel,_.BertTokenizer,_.BitImageProcessor,_.BlenderbotForConditionalGeneration,_.BlenderbotModel,_.BlenderbotPreTrainedModel,_.BlenderbotSmallForConditionalGeneration,_.BlenderbotSmallModel,_.BlenderbotSmallPreTrainedModel,_.BlenderbotSmallTokenizer,_.BlenderbotTokenizer,_.BloomForCausalLM,_.BloomModel,_.BloomPreTrainedModel,_.BloomTokenizer,_.CLIPFeatureExtractor,_.CLIPImageProcessor,_.CLIPModel,_.CLIPPreTrainedModel,_.CLIPSegForImageSegmentation,_.CLIPSegModel,_.CLIPSegPreTrainedModel,_.CLIPTextModel,_.CLIPTextModelWithProjection,_.CLIPTokenizer,_.CLIPVisionModel,_.CLIPVisionModelWithProjection,_.CamembertForMaskedLM,_.CamembertForQuestionAnswering,_.CamembertForSequenceClassification,_.CamembertForTokenClassification,_.CamembertModel,_.CamembertPreTrainedModel,_.CamembertTokenizer,_.CausalLMOutput,_.CausalLMOutputWithPast,_.ChineseCLIPFeatureExtractor,_.ChineseCLIPModel,_.ChineseCLIPPreTrainedModel,_.ClapAudioModelWithProjection,_.ClapFeatureExtractor,_.ClapModel,_.ClapPreTrainedModel,_.ClapTextModelWithProjection,_.ClassifierFreeGuidanceLogitsProcessor,_.CodeGenForCausalLM,_.CodeGenModel,_.CodeGenPreTrainedModel,_.CodeGenTokenizer,_.CodeLlamaTokenizer,_.CohereForCausalLM,_.CohereModel,_.CoherePreTrainedModel,_.CohereTokenizer,_.ConvBertForMaskedLM,_.ConvBertForQuestionAnswering,_.ConvBertForSequenceClassification,_.ConvBertForTokenClassification,_.ConvBertModel,_.ConvBertPreTrainedModel,_.ConvBertTokenizer,_.ConvNextFeatureExtractor,_.ConvNextForImageClassification,_.ConvNextImageProcessor,_.ConvNextModel,_.ConvNextPreTrainedModel,_.ConvNextV2ForImageClassification,_.ConvNextV2Model,_.ConvNextV2PreTrainedModel,_.DPTFeatureExtractor,_.DPTForDepthEstimation,_.DPTImageProcessor,_.DPTModel,_.DPTPreTrainedModel,_.DacDecoderModel,_.DacDecoderOutput,_.DacEncoderModel,_.DacEncoderOutput,_.DacFeatureExtractor,_.DacModel,_.DacPreTrainedModel,_.DataTypeMap,_.DebertaForMaskedLM,_.DebertaForQuestionAnswering,_.DebertaForSequenceClassification,_.DebertaForTokenClassification,_.DebertaModel,_.DebertaPreTrainedModel,_.DebertaTokenizer,_.DebertaV2ForMaskedLM,_.DebertaV2ForQuestionAnswering,_.DebertaV2ForSequenceClassification,_.DebertaV2ForTokenClassification,_.DebertaV2Model,_.DebertaV2PreTrainedModel,_.DebertaV2Tokenizer,_.DecisionTransformerModel,_.DecisionTransformerPreTrainedModel,_.DeiTFeatureExtractor,_.DeiTForImageClassification,_.DeiTImageProcessor,_.DeiTModel,_.DeiTPreTrainedModel,_.DepthAnythingForDepthEstimation,_.DepthAnythingPreTrainedModel,_.DepthEstimationPipeline,_.DepthProForDepthEstimation,_.DepthProPreTrainedModel,_.DetrFeatureExtractor,_.DetrForObjectDetection,_.DetrForSegmentation,_.DetrImageProcessor,_.DetrModel,_.DetrObjectDetectionOutput,_.DetrPreTrainedModel,_.DetrSegmentationOutput,_.Dinov2ForImageClassification,_.Dinov2Model,_.Dinov2PreTrainedModel,_.Dinov2WithRegistersForImageClassification,_.Dinov2WithRegistersModel,_.Dinov2WithRegistersPreTrainedModel,_.DistilBertForMaskedLM,_.DistilBertForQuestionAnswering,_.DistilBertForSequenceClassification,_.DistilBertForTokenClassification,_.DistilBertModel,_.DistilBertPreTrainedModel,_.DistilBertTokenizer,_.DocumentQuestionAnsweringPipeline,_.DonutFeatureExtractor,_.DonutImageProcessor,_.DonutSwinModel,_.DonutSwinPreTrainedModel,_.EfficientNetForImageClassification,_.EfficientNetImageProcessor,_.EfficientNetModel,_.EfficientNetPreTrainedModel,_.ElectraForMaskedLM,_.ElectraForQuestionAnswering,_.ElectraForSequenceClassification,_.ElectraForTokenClassification,_.ElectraModel,_.ElectraPreTrainedModel,_.ElectraTokenizer,_.EncodecFeatureExtractor,_.EosTokenCriteria,_.EsmForMaskedLM,_.EsmForSequenceClassification,_.EsmForTokenClassification,_.EsmModel,_.EsmPreTrainedModel,_.EsmTokenizer,_.ExaoneForCausalLM,_.ExaoneModel,_.ExaonePreTrainedModel,_.FFT,_.FalconForCausalLM,_.FalconModel,_.FalconPreTrainedModel,_.FalconTokenizer,_.FastViTForImageClassification,_.FastViTModel,_.FastViTPreTrainedModel,_.FeatureExtractionPipeline,_.FeatureExtractor,_.FillMaskPipeline,_.Florence2ForConditionalGeneration,_.Florence2PreTrainedModel,_.Florence2Processor,_.ForcedBOSTokenLogitsProcessor,_.ForcedEOSTokenLogitsProcessor,_.GLPNFeatureExtractor,_.GLPNForDepthEstimation,_.GLPNModel,_.GLPNPreTrainedModel,_.GPT2LMHeadModel,_.GPT2Model,_.GPT2PreTrainedModel,_.GPT2Tokenizer,_.GPTBigCodeForCausalLM,_.GPTBigCodeModel,_.GPTBigCodePreTrainedModel,_.GPTJForCausalLM,_.GPTJModel,_.GPTJPreTrainedModel,_.GPTNeoForCausalLM,_.GPTNeoModel,_.GPTNeoPreTrainedModel,_.GPTNeoXForCausalLM,_.GPTNeoXModel,_.GPTNeoXPreTrainedModel,_.GPTNeoXTokenizer,_.Gemma2ForCausalLM,_.Gemma2Model,_.Gemma2PreTrainedModel,_.Gemma3ForCausalLM,_.Gemma3Model,_.Gemma3PreTrainedModel,_.GemmaForCausalLM,_.GemmaModel,_.GemmaPreTrainedModel,_.GemmaTokenizer,_.GlmForCausalLM,_.GlmModel,_.GlmPreTrainedModel,_.GraniteForCausalLM,_.GraniteModel,_.GranitePreTrainedModel,_.Grok1Tokenizer,_.GroundingDinoForObjectDetection,_.GroundingDinoImageProcessor,_.GroundingDinoPreTrainedModel,_.GroundingDinoProcessor,_.GroupViTModel,_.GroupViTPreTrainedModel,_.HeliumForCausalLM,_.HeliumModel,_.HeliumPreTrainedModel,_.HerbertTokenizer,_.HieraForImageClassification,_.HieraModel,_.HieraPreTrainedModel,_.HubertForCTC,_.HubertForSequenceClassification,_.HubertModel,_.HubertPreTrainedModel,_.IJepaForImageClassification,_.IJepaModel,_.IJepaPreTrainedModel,_.Idefics3ForConditionalGeneration,_.Idefics3ImageProcessor,_.Idefics3PreTrainedModel,_.Idefics3Processor,_.ImageClassificationPipeline,_.ImageFeatureExtractionPipeline,_.ImageFeatureExtractor,_.ImageMattingOutput,_.ImageProcessor,_.ImageSegmentationPipeline,_.ImageToImagePipeline,_.ImageToTextPipeline,_.InterruptableStoppingCriteria,_.JAISLMHeadModel,_.JAISModel,_.JAISPreTrainedModel,_.JinaCLIPImageProcessor,_.JinaCLIPModel,_.JinaCLIPPreTrainedModel,_.JinaCLIPProcessor,_.JinaCLIPTextModel,_.JinaCLIPVisionModel,_.LiteWhisperForConditionalGeneration,_.LlamaForCausalLM,_.LlamaModel,_.LlamaPreTrainedModel,_.LlamaTokenizer,_.LlavaForConditionalGeneration,_.LlavaOnevisionForConditionalGeneration,_.LlavaOnevisionImageProcessor,_.LlavaPreTrainedModel,_.LogitsProcessor,_.LogitsProcessorList,_.LogitsWarper,_.LongT5ForConditionalGeneration,_.LongT5Model,_.LongT5PreTrainedModel,_.M2M100ForConditionalGeneration,_.M2M100Model,_.M2M100PreTrainedModel,_.M2M100Tokenizer,_.MBart50Tokenizer,_.MBartForCausalLM,_.MBartForConditionalGeneration,_.MBartForSequenceClassification,_.MBartModel,_.MBartPreTrainedModel,_.MBartTokenizer,_.MPNetForMaskedLM,_.MPNetForQuestionAnswering,_.MPNetForSequenceClassification,_.MPNetForTokenClassification,_.MPNetModel,_.MPNetPreTrainedModel,_.MPNetTokenizer,_.MT5ForConditionalGeneration,_.MT5Model,_.MT5PreTrainedModel,_.MarianMTModel,_.MarianModel,_.MarianPreTrainedModel,_.MarianTokenizer,_.Mask2FormerImageProcessor,_.MaskFormerFeatureExtractor,_.MaskFormerForInstanceSegmentation,_.MaskFormerImageProcessor,_.MaskFormerModel,_.MaskFormerPreTrainedModel,_.MaskedLMOutput,_.MaxLengthCriteria,_.Metric3DForDepthEstimation,_.Metric3DPreTrainedModel,_.Metric3Dv2ForDepthEstimation,_.Metric3Dv2PreTrainedModel,_.MgpstrForSceneTextRecognition,_.MgpstrModelOutput,_.MgpstrPreTrainedModel,_.MgpstrProcessor,_.MgpstrTokenizer,_.MimiDecoderModel,_.MimiDecoderOutput,_.MimiEncoderModel,_.MimiEncoderOutput,_.MimiModel,_.MimiPreTrainedModel,_.MinLengthLogitsProcessor,_.MinNewTokensLengthLogitsProcessor,_.MistralForCausalLM,_.MistralModel,_.MistralPreTrainedModel,_.MobileBertForMaskedLM,_.MobileBertForQuestionAnswering,_.MobileBertForSequenceClassification,_.MobileBertModel,_.MobileBertPreTrainedModel,_.MobileBertTokenizer,_.MobileLLMForCausalLM,_.MobileLLMModel,_.MobileLLMPreTrainedModel,_.MobileNetV1FeatureExtractor,_.MobileNetV1ForImageClassification,_.MobileNetV1ForSemanticSegmentation,_.MobileNetV1ImageProcessor,_.MobileNetV1Model,_.MobileNetV1PreTrainedModel,_.MobileNetV2FeatureExtractor,_.MobileNetV2ForImageClassification,_.MobileNetV2ForSemanticSegmentation,_.MobileNetV2ImageProcessor,_.MobileNetV2Model,_.MobileNetV2PreTrainedModel,_.MobileNetV3FeatureExtractor,_.MobileNetV3ForImageClassification,_.MobileNetV3ForSemanticSegmentation,_.MobileNetV3ImageProcessor,_.MobileNetV3Model,_.MobileNetV3PreTrainedModel,_.MobileNetV4FeatureExtractor,_.MobileNetV4ForImageClassification,_.MobileNetV4ForSemanticSegmentation,_.MobileNetV4ImageProcessor,_.MobileNetV4Model,_.MobileNetV4PreTrainedModel,_.MobileViTFeatureExtractor,_.MobileViTForImageClassification,_.MobileViTImageProcessor,_.MobileViTModel,_.MobileViTPreTrainedModel,_.MobileViTV2ForImageClassification,_.MobileViTV2Model,_.MobileViTV2PreTrainedModel,_.ModelOutput,_.ModernBertForMaskedLM,_.ModernBertForSequenceClassification,_.ModernBertForTokenClassification,_.ModernBertModel,_.ModernBertPreTrainedModel,_.Moondream1ForConditionalGeneration,_.MoonshineFeatureExtractor,_.MoonshineForConditionalGeneration,_.MoonshineModel,_.MoonshinePreTrainedModel,_.MoonshineProcessor,_.MptForCausalLM,_.MptModel,_.MptPreTrainedModel,_.MultiModalityCausalLM,_.MultiModalityPreTrainedModel,_.MusicgenForCausalLM,_.MusicgenForConditionalGeneration,_.MusicgenModel,_.MusicgenPreTrainedModel,_.NllbTokenizer,_.NoBadWordsLogitsProcessor,_.NoRepeatNGramLogitsProcessor,_.NomicBertModel,_.NomicBertPreTrainedModel,_.NougatImageProcessor,_.NougatTokenizer,_.OPTForCausalLM,_.OPTModel,_.OPTPreTrainedModel,_.ObjectDetectionPipeline,_.Olmo2ForCausalLM,_.Olmo2Model,_.Olmo2PreTrainedModel,_.OlmoForCausalLM,_.OlmoModel,_.OlmoPreTrainedModel,_.OpenELMForCausalLM,_.OpenELMModel,_.OpenELMPreTrainedModel,_.OwlViTFeatureExtractor,_.OwlViTForObjectDetection,_.OwlViTImageProcessor,_.OwlViTModel,_.OwlViTPreTrainedModel,_.OwlViTProcessor,_.Owlv2ForObjectDetection,_.Owlv2ImageProcessor,_.Owlv2Model,_.Owlv2PreTrainedModel,_.PaliGemmaForConditionalGeneration,_.PaliGemmaPreTrainedModel,_.PaliGemmaProcessor,_.PatchTSMixerForPrediction,_.PatchTSMixerModel,_.PatchTSMixerPreTrainedModel,_.PatchTSTForPrediction,_.PatchTSTModel,_.PatchTSTPreTrainedModel,_.Phi3ForCausalLM,_.Phi3Model,_.Phi3PreTrainedModel,_.Phi3VForCausalLM,_.Phi3VImageProcessor,_.Phi3VPreTrainedModel,_.Phi3VProcessor,_.PhiForCausalLM,_.PhiModel,_.PhiPreTrainedModel,_.Pipeline,_.PreTrainedModel,_.PreTrainedTokenizer,_.PretrainedConfig,_.PretrainedMixin,_.Processor,_.PvtForImageClassification,_.PvtImageProcessor,_.PvtModel,_.PvtPreTrainedModel,_.PyAnnoteFeatureExtractor,_.PyAnnoteForAudioFrameClassification,_.PyAnnoteModel,_.PyAnnotePreTrainedModel,_.PyAnnoteProcessor,_.QuestionAnsweringModelOutput,_.QuestionAnsweringPipeline,_.Qwen2ForCausalLM,_.Qwen2Model,_.Qwen2PreTrainedModel,_.Qwen2Tokenizer,_.Qwen2VLForConditionalGeneration,_.Qwen2VLImageProcessor,_.Qwen2VLPreTrainedModel,_.Qwen2VLProcessor,_.RTDetrForObjectDetection,_.RTDetrImageProcessor,_.RTDetrModel,_.RTDetrObjectDetectionOutput,_.RTDetrPreTrainedModel,_.RawAudio,_.RawImage,_.RawVideo,_.RawVideoFrame,_.RepetitionPenaltyLogitsProcessor,_.ResNetForImageClassification,_.ResNetModel,_.ResNetPreTrainedModel,_.RoFormerForMaskedLM,_.RoFormerForQuestionAnswering,_.RoFormerForSequenceClassification,_.RoFormerForTokenClassification,_.RoFormerModel,_.RoFormerPreTrainedModel,_.RoFormerTokenizer,_.RobertaForMaskedLM,_.RobertaForQuestionAnswering,_.RobertaForSequenceClassification,_.RobertaForTokenClassification,_.RobertaModel,_.RobertaPreTrainedModel,_.RobertaTokenizer,_.SamImageProcessor,_.SamImageSegmentationOutput,_.SamModel,_.SamPreTrainedModel,_.SamProcessor,_.SapiensForDepthEstimation,_.SapiensForNormalEstimation,_.SapiensForSemanticSegmentation,_.SapiensPreTrainedModel,_.SeamlessM4TFeatureExtractor,_.SegformerFeatureExtractor,_.SegformerForImageClassification,_.SegformerForSemanticSegmentation,_.SegformerImageProcessor,_.SegformerModel,_.SegformerPreTrainedModel,_.Seq2SeqLMOutput,_.SequenceClassifierOutput,_.SiglipImageProcessor,_.SiglipModel,_.SiglipPreTrainedModel,_.SiglipTextModel,_.SiglipTokenizer,_.SiglipVisionModel,_.SmolVLMForConditionalGeneration,_.SmolVLMImageProcessor,_.SmolVLMProcessor,_.SnacDecoderModel,_.SnacEncoderModel,_.SnacFeatureExtractor,_.SnacModel,_.SnacPreTrainedModel,_.SpeechT5FeatureExtractor,_.SpeechT5ForSpeechToText,_.SpeechT5ForTextToSpeech,_.SpeechT5HifiGan,_.SpeechT5Model,_.SpeechT5PreTrainedModel,_.SpeechT5Processor,_.SpeechT5Tokenizer,_.SqueezeBertForMaskedLM,_.SqueezeBertForQuestionAnswering,_.SqueezeBertForSequenceClassification,_.SqueezeBertModel,_.SqueezeBertPreTrainedModel,_.SqueezeBertTokenizer,_.StableLmForCausalLM,_.StableLmModel,_.StableLmPreTrainedModel,_.Starcoder2ForCausalLM,_.Starcoder2Model,_.Starcoder2PreTrainedModel,_.StoppingCriteria,_.StoppingCriteriaList,_.StyleTextToSpeech2Model,_.StyleTextToSpeech2PreTrainedModel,_.SummarizationPipeline,_.SuppressTokensAtBeginLogitsProcessor,_.Swin2SRForImageSuperResolution,_.Swin2SRImageProcessor,_.Swin2SRModel,_.Swin2SRPreTrainedModel,_.SwinForImageClassification,_.SwinForSemanticSegmentation,_.SwinModel,_.SwinPreTrainedModel,_.T5ForConditionalGeneration,_.T5Model,_.T5PreTrainedModel,_.T5Tokenizer,_.TableTransformerForObjectDetection,_.TableTransformerModel,_.TableTransformerObjectDetectionOutput,_.TableTransformerPreTrainedModel,_.TemperatureLogitsWarper,_.Tensor,_.Text2TextGenerationPipeline,_.TextClassificationPipeline,_.TextGenerationPipeline;var ox=_.TextStreamer;_.TextToAudioPipeline,_.TokenClassificationPipeline,_.TokenClassifierOutput,_.TokenizerModel,_.TopKLogitsWarper,_.TopPLogitsWarper,_.TrOCRForCausalLM,_.TrOCRPreTrainedModel,_.TranslationPipeline,_.UltravoxModel,_.UltravoxPreTrainedModel,_.UltravoxProcessor,_.UniSpeechForCTC,_.UniSpeechForSequenceClassification,_.UniSpeechModel,_.UniSpeechPreTrainedModel,_.UniSpeechSatForAudioFrameClassification,_.UniSpeechSatForCTC,_.UniSpeechSatForSequenceClassification,_.UniSpeechSatModel,_.UniSpeechSatPreTrainedModel,_.VLChatProcessor,_.VLMImageProcessor,_.ViTFeatureExtractor,_.ViTForImageClassification,_.ViTImageProcessor,_.ViTMAEModel,_.ViTMAEPreTrainedModel,_.ViTMSNForImageClassification,_.ViTMSNModel,_.ViTMSNPreTrainedModel,_.ViTModel,_.ViTPreTrainedModel,_.VisionEncoderDecoderModel,_.VitMatteForImageMatting,_.VitMatteImageProcessor,_.VitMattePreTrainedModel,_.VitPoseForPoseEstimation,_.VitPoseImageProcessor,_.VitPosePreTrainedModel,_.VitsModel,_.VitsModelOutput,_.VitsPreTrainedModel,_.VitsTokenizer,_.Wav2Vec2BertForCTC,_.Wav2Vec2BertForSequenceClassification,_.Wav2Vec2BertModel,_.Wav2Vec2BertPreTrainedModel,_.Wav2Vec2CTCTokenizer,_.Wav2Vec2FeatureExtractor,_.Wav2Vec2ForAudioFrameClassification,_.Wav2Vec2ForCTC,_.Wav2Vec2ForSequenceClassification,_.Wav2Vec2Model,_.Wav2Vec2PreTrainedModel,_.Wav2Vec2Processor,_.Wav2Vec2ProcessorWithLM,_.WavLMForAudioFrameClassification,_.WavLMForCTC,_.WavLMForSequenceClassification,_.WavLMForXVector,_.WavLMModel,_.WavLMPreTrainedModel,_.WeSpeakerFeatureExtractor,_.WeSpeakerResNetModel,_.WeSpeakerResNetPreTrainedModel,_.WhisperFeatureExtractor;var ax=_.WhisperForConditionalGeneration;_.WhisperModel,_.WhisperPreTrainedModel,_.WhisperProcessor,_.WhisperTextStreamer,_.WhisperTimeStampLogitsProcessor,_.WhisperTokenizer,_.XLMForQuestionAnswering,_.XLMForSequenceClassification,_.XLMForTokenClassification,_.XLMModel,_.XLMPreTrainedModel,_.XLMRobertaForMaskedLM,_.XLMRobertaForQuestionAnswering,_.XLMRobertaForSequenceClassification,_.XLMRobertaForTokenClassification,_.XLMRobertaModel,_.XLMRobertaPreTrainedModel,_.XLMRobertaTokenizer,_.XLMTokenizer,_.XLMWithLMHeadModel,_.XVectorOutput,_.YolosFeatureExtractor,_.YolosForObjectDetection,_.YolosImageProcessor,_.YolosModel,_.YolosObjectDetectionOutput,_.YolosPreTrainedModel,_.ZeroShotAudioClassificationPipeline,_.ZeroShotClassificationPipeline,_.ZeroShotImageClassificationPipeline,_.ZeroShotObjectDetectionPipeline,_.bankers_round,_.cat,_.cos_sim,_.dot,_.dynamic_time_warping,_.env;var lx=_.full;_.full_like,_.getKeyValueShapes,_.hamming,_.hanning,_.interpolate,_.interpolate_4d,_.interpolate_data,_.is_chinese_char,_.layer_norm,_.load_image,_.load_video,_.log_softmax,_.magnitude,_.matmul,_.max,_.mean,_.mean_pooling,_.medianFilter,_.mel_filter_bank,_.min,_.ones,_.ones_like,_.permute,_.permute_data,_.pipeline,_.quantize_embeddings,_.rand,_.read_audio,_.rfft,_.round,_.slice,_.softmax,_.spectrogram,_.stack,_.std_mean,_.topk,_.window_function,_.zeros,_.zeros_like;const dx=64;class Wn{static async getInstance(r){return this.model_id="onnx-community/whisper-large-v3-turbo",this.tokenizer??(this.tokenizer=ix.from_pretrained(this.model_id,{progress_callback:r})),this.processor??(this.processor=nx.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=ax.from_pretrained(this.model_id,{dtype:{encoder_model:"fp16",decoder_model_merged:"q4"},device:"webgpu",progress_callback:r})),Promise.all([this.tokenizer,this.processor,this.model])}}re(Wn,"model_id",null),re(Wn,"tokenizer"),re(Wn,"processor"),re(Wn,"model");async function cx(e){const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n{o??(o=performance.now());let f;a++>0&&(f=a/(performance.now()-o)*1e3),globalThis.postMessage({status:"update",output:w,tps:f,numTokens:a})},d=new ox(s,{skip_prompt:!0,decode_kwargs:{skip_special_tokens:!0},callback_function:l}),p=await i(t),u=await n.generate({...p,max_new_tokens:dx,language:r,streamer:d}),h=s.batch_decode(u,{skip_special_tokens:!0});globalThis.postMessage({status:"complete",output:h}),Xc=!1}async function px(){globalThis.postMessage({status:"loading",data:"Loading model..."});const[e,r,t]=await Wn.getInstance(s=>{globalThis.postMessage(s)});globalThis.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await t.generate({input_features:lx([1,128,3e3],0),max_new_tokens:1}),globalThis.postMessage({status:"ready"})}globalThis.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"load":px();break;case"generate":ux(t);break}})})(); diff --git a/assets/xai-CcYrpCYf.js b/assets/xai-BtPhk-ua.js similarity index 67% rename from assets/xai-CcYrpCYf.js rename to assets/xai-BtPhk-ua.js index e41777e6d890a470beee4214eb3e208db297068d..f99478a95cc98f596459e11b5214999d7d5a7c13 100644 --- a/assets/xai-CcYrpCYf.js +++ b/assets/xai-BtPhk-ua.js @@ -1 +1 @@ -import"./live2d-zip-loader-BdiFCiUD.js";import{d as x,i as U,bE as V,s as y,h as v,m as $,w as k,x as K,o as h,y as p,b as l,e as t}from"./index-rD0Uu1v9.js";import{u as w}from"./providers-Dg3FpvfZ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-B6O5Ed-l.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-D6iZRJ1J.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BB0RLsbB.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-Dspm6e47.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-Dwj6jOSw.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-NdRJmgIO.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-DzP-b4ZK.js";import"./Input.vue_vue_type_script_setup_true_lang-ffn2ynxx.js";const a="xai",H=x({__name:"xai",setup(B){const{t:d}=U(),_=V(),m=w(),{providers:o}=y(m),n=v(()=>m.getProviderMetadata(a)),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,i;m.initializeProvider(a),s.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),k([s,r],()=>{o.value[a]={...o.value[a],apiKey:s.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return h(),K(t(S),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(P),null,{default:p(()=>[l(t(R),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(N),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=g=>s.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"xai-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=u=>r.value=u),placeholder:"https://api.x.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; +import"./live2d-zip-loader-C5j9stxV.js";import{d as x,i as U,bE as V,s as y,h as v,m as $,w as k,x as K,o as h,y as p,b as l,e as t}from"./index-Dlp4W1Zl.js";import{u as w}from"./providers-BRCa7xUS.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-ByRjZiEm.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-CJEkoqPm.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-BmvtPoIO.js";import{_ as S}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BiW-Rh6S.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DB9y2Oef.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-Dch7MbTT.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Dgm67C-D.js";import"./Input.vue_vue_type_script_setup_true_lang-BOLdlSh_.js";const a="xai",H=x({__name:"xai",setup(B){const{t:d}=U(),_=V(),m=w(),{providers:o}=y(m),n=v(()=>m.getProviderMetadata(a)),s=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.apiKey)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].apiKey=e}}),r=v({get:()=>{var e;return((e=o.value[a])==null?void 0:e.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});$(()=>{var e,i;m.initializeProvider(a),s.value=((e=o.value[a])==null?void 0:e.apiKey)||"",r.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),k([s,r],()=>{o.value[a]={...o.value[a],apiKey:s.value,baseUrl:r.value||""}});function b(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return h(),K(t(S),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(P),null,{default:p(()=>[l(t(R),{title:t(d)("settings.pages.providers.common.section.basic.title"),description:t(d)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var u;return[l(t(N),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=g=>s.value=g),"provider-name":(u=n.value)==null?void 0:u.localizedName,placeholder:"xai-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(d)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=u=>r.value=u),placeholder:"https://api.x.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});export{H as default}; diff --git a/index.html b/index.html index f62135752c84b3fc7bb7e5bd90a6cff354f8898c..1fcda545f1976b8c35232c3d2b8bebe8aac02428 100644 --- a/index.html +++ b/index.html @@ -23,7 +23,7 @@ src="/remote-assets/page-external-data/js/script.js" > - +